var ajaxUrl = '/cgi/Policy/OrdinaryPolicyPersistence.ashx';
var elB = new Elass.Base();
var objPolicy;
var oldPolicy;
var isFocus = false;//是否聚焦
var isLoaded = false;
var airLineOctr = [
{ 'S': 1, 'E': '境内→境外', 'D': '0', 'T': '', 'A': '1' }, //国内始发
{ 'S': 1, 'E': '境外→境内', 'D': '1', 'T': '', 'A': '0' }, //直飞SOTO程
{ 'S': 1, 'E': '境内→境内→境外', 'D': '0', 'T': '0', 'A': '1' }, //国内始发Add-On
{ 'S': 1, 'E': '境外→境内→境内', 'D': '1', 'T': '0', 'A': '0' }, //国外始发Add-On
{ 'S': 0, 'E': '', 'D': '', 'T': '', 'A': '' }, //缺口程
{ 'S': 0, 'E': '', 'D': '', 'T': '', 'A': '' }, //Spa
{ 'S': 1, 'E': '境外→境外', 'D': '1', 'T': '', 'A': '1' }, //境外到境外
{ 'S': 1, 'E': '境内→境外→境外', 'D': '0', 'T': '1', 'A': '1' }, //国内始发中转
{ 'S': 1, 'E': '境外→境外→境内', 'D': '1', 'T': '1', 'A': '0' }, //国外始发中转
{ 'S': 1, 'E': '境外→境外→境外', 'D': '1', 'T': '1', 'A': '1' }, //境外境外境外
{ 'S': 1, 'E': '境外→境内→境外', 'D': '1', 'T': '0', 'A': '1' }, //境外境内境外
{ 'S': 1, 'E': '全球→全球', 'D': '2', 'T': '', 'A': '2' }, //全球到全球
{ 'S': 1, 'E': '全球→全球→全球', 'D': '2', 'T': '2', 'A': '2' } //全球中转全球
];  //境外境内境外
function GetCurrency(isasync) {
    if (isExtProvider || (!isExtProvider && IsAddEtermConfigSupply)) {
        var ticketPlace = $('#txt_TicketPlace');
        var tickeplaceVal = $.trim(ticketPlace.val())
        if (tickeplaceVal == '' || ticketPlace.is(":hidden")) {
            return;
        }
    } else {
        $("span[name='currtype']").each(function (i, n) {
            $(n).html(currTypeTemp);
        });
        currType = currTypeTemp;
        currencyRate = currencyRateDefaultRate;
    }
}

$(document).ready(function () {
    initPage();
    regEvent();
    fillData();
    window.setTimeout(function () { initSpecial(); }, 500);
    function initPage() {
        initFlightType();
        initCategoryHtml();
        initChildrenHtml();
        initBabyHtml();
        initObType();
        initChangePnrHtml();
        initAdaptHtml();
        initWorkTime();
        initDateRange();
        initOther();
        restDefault();
        initLoading();//add by qiuzhicheng 2015.02.02 GJGD-707
    }

    function initOther() {
        $('input._date_Ipt').addClass('tim_img2').focus(function () {
            $(this).removeClass('tim_img2').addClass('tim_img1');
        }).blur(function () {
            $(this).removeClass('tim_img1').addClass('tim_img2');
        });
        $('input[type=text]').addClass('inpt');
        $(':text[data-empty]').emptyValue();
        $('#btn_Save').val(policyID == '' ? $('#btn_Save').attr('va') : $('#btn_Save').attr('ve'));
        //add by qiuzhicheng 2015.03.23 begin
        if (policyID != '') {
            $('#txt_AirLine').attr('disabled', 'disabled');
            if (copyObTypeNum != '') {
                $('#txt_AirLine').removeAttr('disabled');
            }
        }
        //add by qiuzhicheng 2015.03.23 end
        $("#hidgds").hide();
        //add by yejianliang 2015.10.16

        if (!isExtProvider) {
            $("#Sgds option[value='0']").html("境内Eterm");
            //$("#Sgds").append("<option value='0'>境内Eterm</option>");
            //$("#Sgds option[value='1']").remove();
            $('#bitianOpenTicket').removeClass("bitian");
        }
    }

    function initSpecial() {
        if (isSpecialAccount == '1') {
            $('.specialAcc').show();
        }
        else {
            if (copyObTypeNum != '') {
                $('.specialAcc').each(function (i, m) {
                    $(m).hide();
                    var ipts = $(':input', m);
                    for (var j = 0; j < ipts.length; j++) {
                        if (ipts[j].type == 'checkbox' && ipts[j].checked == true) {

                            $(m).show();
                        }
                        $(ipts[j]).attr("disabled", "disabled");
                    }

                });
            }
            $('#sp_IsChildren :radio[value=C]').attr('disabled', 'disabled');
        }
    }
    function initObType() {
        var dv = $('#td_ObTypeNum');
        //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
        //for (var i = 0; i < airLineOctr.length; i++) {
        //    if (i == 5) {
        //        dv.append('<br/>');
        //    }
        //    if (airLineOctr[i].S == 1) {
        //        var o = $(C.Dom.getRadioHtml('rd_ObTypeNum', ObTypeCodeData[i].Key, ObTypeCodeData[i].Name));
        //        o.find(':radio').data('Octr', airLineOctr[i]);
        //        o.attr('title', airLineOctr[i].E);
        //        dv.append(o);
        //    }
        //}

        var changeLine = 6;//换行
        var index = 0;
        for (var i = 0; i < airLineOctr.length; i++) {
            if (index == changeLine) {
                dv.append('<br/>');
            }
            if (airLineOctr[i].S == 1) {
                var rdoText = ObTypeCodeData[i].Name;
                if (ObTypeCodeData[i].Key == '0115' || ObTypeCodeData[i].Key == '0116') {//全球选项粗体，鼓励用户选择
                    rdoText = '<font style="font-weight:bold;">' + rdoText + '</font>';
                }
                var o = $(C.Dom.getRadioHtml('rd_ObTypeNum', ObTypeCodeData[i].Key, rdoText));
                o.find(':radio').data('Octr', airLineOctr[i]);
                o.attr('title', airLineOctr[i].E);
                dv.append(o);
                index++;
            }
        }
        //edit by qiuzhicheng 2015.02.02 GJGD-707 end
        dv.find(':radio[value=1010]').attr('checked', 'checked');
    }
    function initFlightType() {
        var h = '';
        for (var i = 0; i < FlightCodeData.length - 1; i++) {
            h += C.Dom.getCheckBoxHtml(FlightCodeData[i].Key, FlightCodeData[i].Name);
        }
        $('#td_FlightType').html(h);
    }
    function initCategoryHtml() {
        var h = '';
        for (var i = 0; i < CategoryData.length; i++) {
            h += C.Dom.getCheckBoxHtml(CategoryData[i].Key, CategoryData[i].Name);
        }
        $('#td_IsCategory').html(h).find(':checkbox[value=A]').attr('checked', 'checked');
    }
    function initWorkTime() {
        $('select[dateType]').each(function (i) {
            $(this).css('width', '41px');
            switch ($(this).attr('dateType')) {
                case 'H':
                    $(this).html(getWorkTimeOptionsHtml(0, 23));
                    break;
                case 'M':
                    $(this).html(getWorkTimeOptionsHtml(0, 59));
                    break;
                default: break;
            }
            if ($(this).attr('defaultValue')) {
                $(this).val($(this).attr('defaultValue'));
            }
        });
        function getWorkTimeOptionsHtml(start, end) {
            var h = '';
            for (var i = start; i <= end; i++) {
                var v = i + '';
                if (i < 10) {
                    v = '0' + v;
                }
                h += C.Dom.getSelectOption(v, v);
            }
            return h;
        }
    }
    function initChildrenHtml() {
        initRadioList('#sp_IsChildren', ChildrenData, 'rd_IsChildren', 'A');
    }
    function initBabyHtml() {
        initRadioList('#sp_IsBaby', BabyData, 'rd_Baby', 'A');
    }
    function initChangePnrHtml() {
        initRadioList('#dv_IsChangePnr', IsChangePnrData, 'rd_ChangePnr', 'D');
    }
    function initRadioList(selector, data, name, v) {
        var h = '';
        for (var i = 0; i < data.length; i++) {
            h += C.Dom.getRadioHtml(name, data[i].Key, data[i].Name);
        }
        $(selector).html(h).find(':radio[value=' + v + ']').attr('checked', 'checked');
    }
    function initAdaptHtml() {
        var h = '';
        var h2 = '';//edit by qiuzhicheng 2015.04.02 GJGD-1262 将IT/BT票面无奖励一行的控件放入div_ITPriceNoReward
        var splitArr = new Array();
        splitArr.push(6, 9, 14);//edit by qiuzhicheng 2015.04.02 GJGD-1207
        var splitIdx = 0;
        for (var i = 0; i < AdaptData.length; i++) {
            h += C.Dom.getCheckBoxHtml(AdaptData[i].Key, AdaptData[i].Name);
            if (splitIdx >= 0 && i == splitArr[splitIdx]) {
                h += '<br/>';
                splitIdx++;
                if (splitIdx >= splitArr.length) {
                    splitIdx = -1;
                }
            }
        }
        h2 += '<div class="_special specialAcc">' + C.Dom.getCheckBoxHtml('1', 'IT/BT票面无奖励', 'cb_ITPriceNoReward')
                    + C.Dom.getCheckBoxHtml('', 'IT/BT票面加收手续费', 'cb_ITPriceMoreAddFee')
                    + '<input id="txt_ITPriceMoreAddFee" maxlength="3" fm="RE" disabled="disabled" class="_disable_Ipt _float_Ipt" type="text" /><span name="currtype">' + currType + '</span></div>';
        h += '<div style="display:none;">' + C.Dom.getCheckBoxHtml('', 'TOUR CODE(旅行代码)', 'cb_TourCode')
           //GJGD-1024 修改录入方式 2015-3-3 modify by lihui 
            //+ '<label><input type="radio" name="rd_TourCode" disabled="disabled" /> 首字母或包含字母</label>'
            //+ '<input id="txt_TourCode" tletype="p" disabled="disabled" class="_disable_Ipt" regtxt="^[a-zA-Z]+$" maxlength="1" type="text" data-empty="例：N" style="width:40px" />'
            //+ '<label><input type="radio" name="rd_TourCode" disabled="disabled" /> 完整代码</label>'
            + '<input id="txt_TourCodeLong" tletype="p" disabled="disabled" class="_disable_Ipt" regtxt="^[a-zA-Z0-9]+$" maxlength="20" type="text" data-empty="例：SHAR001" style="width:246px" /></div>';

        //GJGD-1024 end 

        //h += '<div>' + C.Dom.getCheckBoxHtml('', '指定机场转机', 'cb_TransitAirport')
        //    + '<input id="txt_TransitAirport" tletype="p" fm="RE" disabled="disabled" regtxt="([a-zA-Z]{3}/+([a-zA-Z]{3}/|[a-zA-Z]{3}))|[a-zA-Z]{3}/|[a-zA-Z]{3}" class="_disable_Ipt" type="text" data-empty="例：HKG/MFM/NRT" style="width:300px"/></div>';

        //edit by qiuzhicheng 2015.04.02 GJGD-1262 begin
        //$('#td_IsAdapt').html(h).find('#cb_ITPriceNoReward').attr('cb', 'RE').addClass("num");
        $('#td_IsAdapt').html(h);
        //Add by zhengbo 2015-12-23 GJGD-2694
        $("input:checkbox[value='S']", $("#td_IsAdapt")).attr("onClick", "this.checked=!this.checked").parent().attr('style', 'color:#888');

        $('#div_ITPriceNoReward').html(h2).find('#cb_ITPriceNoReward').attr('cb', 'RE').addClass("num");
        $('#div_ITPriceNoReward').find("#cb_IsTimeOutReward").attr("cb", "R").addClass("num");
        //edit by qiuzhicheng 2015.04.02 GJGD-1262 end
        $('#td_IsAdapt').find('#cb_TourCode').attr('cb', 'RE');
        $('#td_IsAdapt').find('#cb_TransitAirport').attr('cb', 'RE');
        //GJGD-1024 修改录入方式 2015-3-3 modify by lihui 
        $('#td_IsAdapt').find('#cb_TourCode').click(function () {
            //C.Dom.setDisabled($("input[name='rd_TourCode']"), this.checked);
            //C.Dom.setDisabled($("#txt_TourCode"), $($("#txt_TourCode").prev()[0]).children()[0].checked && !$($("#txt_TourCode").prev()[0]).children()[0].disabled);
            C.Dom.setDisabled($("#txt_TourCodeLong"), $($("#txt_TourCodeLong").prev()[0]).children()[0].checked);
        });
        $('input[name="rd_TourCode"]').click(function () {
            C.Dom.setDisabled($("input[name='rd_TourCode']").parent().next(), false);
            C.Dom.setDisabled($($(this).parent().next()[0]), this.checked);
        });
        //GJGD-1024 end
    }
    function initDateRange() {//不适用日期范围
        var arg = { inputClass: '_date_Ipt inpt tim_img2', minDate: new Date(), maxDate: 'txt_SaleEDate' };
        $('#td_UnApplyTimeS').dateRange(arg);
        //add by qiuzhicheng 2015.04.24 begin
        arg.minDate = 'txt_SaleSDate';
        arg.maxDate = 'txt_EReturnTrip';
        //add by qiuzhicheng 2015.04.24 end
        $('#td_UnApplyTimeE').dateRange(arg);
    }

    //GJJSZC-551  2015-2-25 add by lihui
    $("#txt_SaleSDate,#txt_SaleEDate").blur(function () {
        var sdate = new Date($("#txt_SaleSDate").val().replace(/-/g, '/'));
        var edate = new Date($("#txt_SaleEDate").val().replace(/-/g, '/'));
        //GJGD-1051 2015-3-9 add by lihui
        if (sdate > edate) {
            alert("结束日期不能早于开始日期，请重新选择有效期结束日期！");
            $("#txt_SaleEDate").val('');
            return;
        }
        if ($("#txt_EReturnTrip").val() != "" && new Date($("#txt_EReturnTrip").val().replace(/-/g, '/')) < edate) {
            alert("政策有效期已修改，回程有效期延用日期不可用，请重新选择");
            $("#txt_EReturnTrip").val('');
            return;
        }
        //GJGD-1051 end
        //edit by qiuzhicheng 2015.04.24 begin        
        //if ($(".dateRange") != null)
        //{
        //    $(".dateRange a").each(function () {
        //        var arr = $(this).html().split('—');
        //        if (new Date(arr[0].replace(/-/g, '/')) < sdate || new Date(arr[1].replace(/-/g, '/')) > edate) {
        //            $(this).click();
        //            alert("政策有效期已修改，部分不适用日期不可用，如需要请重新添加");
        //            return false;
        //        }
        //    });
        //}

        var bln = true;
        $("#td_UnApplyTimeS .dateRange a").each(function () {
            var arr = $(this).html().split('—');
            if (new Date(arr[0].replace(/-/g, '/')) < sdate || new Date(arr[1].replace(/-/g, '/')) > edate) {
                $(this).click();
                alert("政策有效期已修改，部分不适用日期不可用，如需要请重新添加");
                bln = false;
                return false;
            }
        });
        if (!bln) {
            return;
        }
        var eReturn = new Date($("#txt_EReturnTrip").val().replace(/-/g, '/'));
        $("#td_UnApplyTimeE .dateRange a").each(function () {
            var arr = $(this).html().split('—');
            if (eReturn) {
                if (new Date(arr[0].replace(/-/g, '/')) < sdate || new Date(arr[1].replace(/-/g, '/')) > eReturn) {
                    $(this).click();
                    alert("政策有效期已修改，部分不适用日期不可用，如需要请重新添加");
                    return false;
                }
            }
        });
        //edit by qiuzhicheng 2015.04.24 end
    });
    //GJJSZC-551

    function regEvent() {

        $('#txt_TicketPlace').blur(function () {
            GetCurrency(true);
        });


        $('#Sgds').change(function () {
            var val = $('#Sgds').val();

            if (val == "0") {
                Hidden();
            }
            else {
                ShowEle();
            }
            TicketPlaceIsShow();
            //AutoChangePnrSet();
            setTourCodeRemarkDisplay();

            //GJGD-4701 政策新增GDS换编选项（判断GDS换编选项显示与否）
            //var bsp = $('#td_IsCategory input[type="checkbox"]:checked').val();
            //if (bsp != null && bsp == 'C' && (val == '2' || val == '3' || val == '4')) {
            //    $('#hsGDSChange').show();
            //    $('#hsOLDChange').hide();
            //}
            //else {
            //    $('#hsGDSChange').hide();
            //    $('#hsOLDChange').show();
            //}
            //GJGD-4701 政策新增GDS换编选项（判断GDS换编选项显示与否）

        });

        //GJGD-4118
        ticketPostponed('cb_RefundGrade');
        ticketPostponed('cb_RescheduledGrade');
        ticketPostponed('cb_IsHolidaySales');
        ticketPostponed('cb_DrawerTicket');
        ticketPostponed('cb_LimitTicketDate');

        ticketPostponed2('cb_ShowPlatform');


        //开票OFFICE号内容变更则清空大客户协议
        var index_bspAuto = 0;
        $("#txt_TicketOffice").change(function () {
            if ($("#cb_IsAuto").is(":checked")) {
                $("input:checkbox[name='cb_IsThreeAgreement']").removeAttr('checked');
                $("#sl_AgentCode").val("").html("");
            }
        }).blur(function () {
            if (index_bspAuto != 0 || oldPolicy == null) {
                var iscategory = $("#td_IsCategory").find("input[type='checkbox']:checked").first().val();
                var office = $("#txt_TicketOffice").val();
                BspAutoTicketIsChecked(iscategory, office, false);
            }
            index_bspAuto++;
        });


        $('#cb_Isguarantees').click(function (e) {
            var ele = $('#cb_Isguarantees');
            if (ele.is(":checked")) {

                $('#RetreatTicket').show();
                document.getElementById("txt_RetreatTicketDiscount").disabled = false;

                var discountval = $.trim($('#txt_Discount').val());
                var agioval = $.trim($('#txt_Agio').val());
                var agioValue = parseFloat(agioval == '' ? '0' : agioval) + 0.2;
                $('#txt_RetreatTicketDiscount').val(discountval == '' ? '0' : discountval);
                $('#txt_RetreatTicketAgio').val(agioValue.toFixed(1));


            }
            else {
                $('#RetreatTicket').hide();
                document.getElementById("txt_RetreatTicketDiscount").disabled = true;
            }


        });
        $('#btn_TicketPlace').click(function () {
            var T_001 = new Elass.Base();
            //app.open({
            //    tle: "汇率设置",
            //    css: "margin: 50px;overflow-x:hidden;overflow-y:auto;",
            //    url: "/Provider/ExchangeRate/ChangeRateManager.aspx",
            //    back: false,
            //    drop: true,//禁止拖动
            //    isMin: true,
            //    ready: function () {
            //        $('.ElassBase .bb_2, .ElassBase .bb_3, .ElassBase .bb_4').hide();//隐藏最大，最小，刷新按钮
            //    },
            //    width: 800, height: 500,
            //    cfun: function () {
            //     //   window.location.href = "InvoiceApply.aspx?r=0.41361529170594013";
            //        //$("html").css({ "overflow": defaultOverflowCss }); //add by qiuzhicheng 2015.02.02 GJGD-707 恢复父画面滚动条
            //        //  window.parent.location.href = "InvoiceApply.aspx";
            //        //			        //修改完要清除自动启用时间显示
            //        //			        var tr = $('tr[pid=' + pid + '] ');
            //        //			        tr.find('td:has(span[autoSetTime])').html('<span autoSetTime=\'1\' ></span>');
            //    }

            //});


            T_001.confirm({
                tle: "汇率",
                msg: " <h3 class=\"ff-ac\" style=\"float:right;margin-right:150px\">\
                     1\
                    <select id=\"selCode\"  runat=\"server\">\
                    </select><strong >=</strong>\
                    <input type=\"text\" id=\"txtRateValue\" value=\"1\" />\
                    <strong >：CNY(人民币)</strong>&nbsp;&nbsp;&nbsp;&nbsp;\
                     <button type=\"submit\" id=\"btnUpdate\">添加</button>\
                    <span id=\"error\" style=\"color: red; margin-left: 10px;\"></span>\
                </h3>\
                    ",
                width: 500,
                buttonList: [{
                    text: '确定',
                    bak: function () {
                        T_001.hide();
                    }
                },
                {
                    text: '取消',
                    bak: function () {
                        T_001.hide();
                    }
                }]
            });
        });


        $("input:checkbox[name='cb_IsThreeAgreement']").click(function () {
            if ($(this).is(":checked")) {
                $(this).attr('checked', 'checked').siblings().removeAttr('checked');
                var type = $(this).val();
                fileThreeAuto(type);
            } else {
                $("#sl_AgentCode").val("").html("");
            }
        })

        $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").change(function () {
            $(this).attr('checked', 'checked').siblings().removeAttr('checked');
        })


        $("#txt_OnlyApplyNationality").blur(function () {
            if ($(this).val().trim() != "") {
                $("input:checkbox[value='T']", $("#td_IsAdapt")).attr('disabled', 'disabled');
                $("input:checkbox[value='M']", $("#td_IsAdapt")).attr('disabled', 'disabled');
                this.value = this.value.toUpperCase();
            } else {
                $("input:checkbox[value='T']", $("#td_IsAdapt")).removeAttr('disabled');
                $("input:checkbox[value='M']", $("#td_IsAdapt")).removeAttr('disabled');
            }
        })


        $('#td_FlightType :checkbox').click(function () {//单程、往返
            var selector = '#txt_OneSubtracting';
            if ($(this).val() == '1') {
                selector = '#txt_RoundSubtracting';
                var prt = $('#txt_EReturnTrip').parent().parent();
                C.Dom.setVisibility($('td:gt(1)', prt), this.checked);
                prt = $('#td_UnApplyTimeE').parent();
                C.Dom.setVisibility($('td:gt(1)', prt), this.checked);
                C.Dom.setDisplay($("#dv_ReturnAirport"), this.checked);
                if (!this.checked) {
                    $("#txt_EReturnTrip").val('');
                    $("#txt_ReturnAirport").val('');
                    $("#dv_RetrunAirportType :radio")[1].click();
                    $("#td_UnApplyTimeE .dateRange").html('');
                }
                setRoundMustSpaceDisabled();
                if ($(this).is(":checked")) {
                    $(".td_DurationDay").show();
                } else {
                    $(".td_DurationDay").hide();
                }
            }
            C.Dom.setDisabled(selector, this.checked);
            $(selector).blur();
        });
        $('#td_ObTypeNum :radio').click(function () {//航班类型
            if ($(this).attr('loaded') == '1') {//如果已经选中过了，则不再触发事件
                return;
            }
            $('#td_ObTypeNum :radio').removeAttr('loaded');
            $(this).attr('loaded', '1');
            $('#sp_PolicyTitle').html($(this).parent().text() + '政策');
            reInitAirport();

            //国内始发：1010；直飞SOTO程：1001；国内始发Add-On：0110；国外始发Add-On：0101；
            //国外始发中转：0113；国内始发中转：0111；境外到境外：0010；境外境外境外：0112；
            //境外境内境外：0114；全球到全球：0115；全球中转全球：0116；
            if (this.value == '0110' || this.value == '0101' || this.value == '0113' || this.value == '0111'
                || this.value == '0112' || this.value == '0114' || this.value == '0116') {

                if (this.value == '0110' || this.value == '0101') {
                    //GJJSZC-498 2015-1-6 modify by lihui
                    $("input:checkbox[value='V']", $("#td_IsAdapt")).removeAttr("checked");
                    $("input:checkbox[value='V']", $("#td_IsAdapt")).attr("disabled", "disabled");
                }
                else
                    $("input:checkbox[value='V']", $("#td_IsAdapt")).removeAttr("disabled");

                $("input:checkbox[value='W']", $("#td_IsAdapt")).removeAttr("checked");
                $("input:checkbox[value='W']", $("#td_IsAdapt")).attr("disabled", "disabled");
            }
            else {
                $("input:checkbox[value='V']", $("#td_IsAdapt")).removeAttr("disabled");
                $("input:checkbox[value='W']", $("#td_IsAdapt")).removeAttr("disabled");
            }
            //add by dsp on 2015-3-4 --end  GJGD-932
        });
        $("input[type='text']").bind("blur", function () {
            //日期控件不绑定此方法
            if ($(this).attr("class") == undefined || $(this).attr("class").indexOf("_date") < 0) {
                CheckInput(this);
            }
        });
        $("select").bind("blur", function () {
            CheckInput(this);
        })
        $("#td_IsCategory :checkbox").click(function () {

            //GJGD-791 2015- 票本类型字段增加："BOP" 票本类型 值
            if (this.checked == true) {
                //if (this.value == 'C' || this.value == 'D') {
                $("#td_IsCategory :checkbox[value!='" + this.value + "']").removeAttr("checked");
                //}
                //else
                //$("#td_iscategory :checkbox[value!='a'][value!='b']").removeattr("checked");

                NoSetIsEmptyCodeTicketIsShow();

                if (this.value == 'C') {
                    $("#hidgds").show();
                    var sgdsVal = $('#Sgds').val();
                    $(".span_TicketOffice").html("开票PCC号：");//Add by zhengbo 2015-9-8 GJGD-2

                    //GJGD-4118
                    $(".GJGD-4079").show();
                }
                else {
                    $("#hidgds").hide();
                    $(".span_TicketOffice").html("开票OFFICE号：");//Add by zhengbo 2015-9-8 GJGD-2

                    //GJGD-4118
                    $(".GJGD-4079").hide();
                }
                if (this.value == 'A' || this.value == 'B' || $("#Sgds").val() == '0') {
                    Hidden();

                    var office = $("#txt_TicketOffice").val();
                    BspAutoTicketIsChecked(this.value, office, false);

                }
                else {
                    ShowEle();
                }
                //AutoChangePnrSet();
            }

        });

        //Add by zhengbo 2015-9-8 GJGD-2044
        $('#td_IsCategory input:checkbox[value="C"]').click(function () {
            if (this.checked) {
                $("#hidgds").show();
                $(".span_TicketOffice").html("开票PCC号：");

                //GJGD-4118
                $(".GJGD-4079").show();
            } else {
                $("#hidgds").hide();
                $(".span_TicketOffice").html("开票OFFICE号：");

                //GJGD-4118
                $(".GJGD-4079").hide();
            }
            //AutoChangePnrSet();
        });
        //End GJGD-2044


        $('#sp_IsChildren :radio').click(function () {
            C.Dom.setDisabled('#txt_ChildrenRate', $(this).val() == 'D');
            if ($(this).val() == 'C') {
                $("#cb_ChildrenFee").removeAttr('checked').click().removeAttr('checked');
            }
            C.Dom.setDisabled('#cb_ChildrenFee', $(this).val() != 'C');
        });
        $('#dv_RetrunAirportType :radio').click(function () {
            C.Dom.setDisabled('#txt_RetrunAirport', $(this).val() == '3');
            //add by qiuzhicheng 20150615 begin
            //指定返回国家或机场范围显示提示文字
            if (!$('#dv_RetrunAirportType :radio[value=3]').is(':checked')) {
                $('#txt_RetrunAirport').emptyValue();
            }
        });
        $('#sp_IsBaby :radio').click(function () {
            if ($(this).val() == 'B') {
                $("#cb_BabyFee").removeAttr('checked').click().removeAttr('checked');
            }
            C.Dom.setDisabled('#cb_BabyFee', $(this).val() == 'A');
        });
        $('#cb_IsAuto').click(function () {
            C.Dom.setDisplay($('#tr_AutoSet,#tr_AutoSetTwo,#tr_LuggageAllowanceValue'), this.checked);
            C.Dom.setDisplay($('#tr_SpecialTimeSet'), this.checked);
            setTourCodeRemarkDisplay();
            NoSetIsEmptyCodeTicketIsShow();

            if ($(this).is(':checked')) {
                var iscategory = $("#td_IsCategory").find("input[type='checkbox']:checked").first().val();
                var office = $("#txt_TicketOffice").val();

                if (office != '' && iscategory == 'A') {
                    BspAutoTicketIsChecked(iscategory, office, false);
                }
            } else {
                $(".tip_IsAuto").hide();
                $(".tip_IsAuto2").hide();
            }
        });

        //$('#cb_IsAutoRefund').click(function () {
        //    C.Dom.setDisplay($('#td_RefundType'), this.checked);
        //});

        $('#cb_ChildrenFee,#cb_BabyFee,#cb_NotApplicableAirLine,#cb_ApplyFlightG,#cb_ApplyFlightR,#cb_UnApplyFlight,#cb_Price,#cb_ITPriceMoreAddFee,#cb_FareBasisCodeInclude,#cb_RoundMustSpace,#cb_TourCode,#cb_TransitAirport,#cb_AgentCode,#cb_AutoAgent,#cb_ParValue,#cb_TourCodeInclude').click(function () {
            var t = $('#txt' + $(this).attr('id').substr(2));
            C.Dom.setDisabled(t, this.checked);
            //t.blur();
            if ($(this).attr('id') == "cb_Price") {
                var t = $("#txt_PriceEnd");
                C.Dom.setDisabled(t, this.checked);
            }

            if (this.checked == false && $(this).attr('id') == "cb_ShareFlightDiscount") {
                $("#txt_ShareFlightDiscount").val("");
            }
        });
        //$("#drpLstPrice").change(function () {
        //    changeTxtPriceTip();
        //});
        $('#cb_FareBasisCodeInclude').click(function () {
            C.Dom.setDisabled(':radio[name=rd_FareBasisCodeIncludeNOClose]', this.checked, true);
            // $('#cb_ApplicableFreightBase').removeAttr('checked');
            // C.Dom.setDisabled($('#txt_ApplicableFreightBase'), $('#cb_ApplicableFreightBase').checked, false);
        });
        $('#cb_TourCodeInclude').click(function () {
            if (this.checked) {
                $("#cb_TourCodeNoAgentFee").removeAttr("disabled").val(1);
                $("#cb_TourCodeNoReward").removeAttr("disabled").val(1);
            } else {
                $("#cb_TourCodeNoAgentFee").attr("disabled", "disabled").removeAttr("checked").val(0);
                $("#cb_TourCodeNoReward").attr("disabled", "disabled").removeAttr("checked").val(0);
            }
        });
        $('#cb_ApplicableFreightBase').click(function () {
            C.Dom.setDisabled($("#txt_ApplicableFreightBase"), this.checked, false);
            //$('#cb_FareBasisCodeInclude').removeAttr('checked');
            //    C.Dom.setDisabled(':radio[name=rd_FareBasisCodeIncludeNOClose]', $('#cb_FareBasisCodeInclude').checked, true);
            //  C.Dom.setDisabled($('#txt_FareBasisCodeInclude'), $('#cb_FareBasisCodeInclude').checked, false);
        })
        $('#cb_WeekEnd,#cb_Sunday,#cb_Rest,#cb_AutoSpecial').click(function () {
            var sel = $(this).parent().parent().parent().find('select');
            C.Dom.setDisabled(sel, !this.checked, true);
        });
        $('#txt_AirLine').focus(function () {
            AirlineCode('txt_AirLine', 'hd_AirLine', function (key, name) {
                AutoChangePnrSet();
            });
        });
        $('#btn_Save').click(function () {
            if (!CheckInput())
                return;
            btnSave_click();
        });
        $('#div_ProtocolType input:radio').click(function () {
            if ($(this).attr('value') == '2') {
                $('.clsProtocol').css('display', '');
            } else {
                $('.clsProtocol').css('display', 'none');
            }
        });
        $('#cb_IsReward').click(function () {
            if ($(this).is(':checked')) {
                $('#cb_RoundMustSpace').removeAttr('checked');
                C.Dom.setDisabled($('#txt_RoundMustSpace'), false);
            }
        });
        $('#cb_RoundMustSpace').click(function () {
            if ($(this).is(':checked')) {
                $('#cb_IsReward').removeAttr('checked');
            }
        });
        $('#td_IsCategory input:checkbox').click(function () {
            setIsChildren();
            setMustProviderReviewDisabled();
        });

        $('#td_ShareflightMade input:radio,input:checkbox').click(function () {
            setShareFlight();
        });

        $('#txt_Agio,#txt_OneSubtracting,#txt_RoundSubtracting').blur(function () {
            setIsChildren();
        });
        $('#cb_NoOutTicketOffice').click(function () {
            setNoOutTicketOfficeClick();
        });

        $("#rd_NotchProcess").find("input[type='radio']").click(function () {
            if ($(this).is(':checked') && $(this).val() != 3) {
                $("#txt_NotchProcessCity").attr('disabled', 'disabled').val("");
            } else {
                $("#txt_NotchProcessCity").removeAttr('disabled', 'disabled');
            }
        })

    }
    function initBefore(v) {
        if (v) {
            $('#dv_InitAirport').show();
            $('#dv_CitiesC').hide();
        }
        else {
            $('#dv_InitAirport').hide();
            $('#dv_CitiesC').show();
        }
    }
    function initLoading() {
        var img = $('#dv_InitAirport img');
        img.css({
            "top": ($(window).height() + $(document).scrollTop()) / 2,
            "left": ($(window).width()) / 2,
            "display": "block",
            "position": "absolute"
        });
    }
    function initAllAirPort() {
        initBefore();
        initAirPort(getAllAirports());
        initBefore(false);
    }
    function getAllAirports() {
        return eval('(' + $('#lbl_AllAirports').text() + ')');
    }
    function reInitAirport() {//重新构造机场选择插件
        var obtOct = $('#td_ObTypeNum :radio:checked').data('Octr');
        $('#dv_DepCity').airPortSelect(obtOct.D, 'reInit');
        $('#dv_TransferCity').airPortSelect(obtOct.T, 'reInit');
        $('#dv_ArrCity').airPortSelect(obtOct.A, 'reInit');

        if (obtOct.T.length == 0) {
            $('#dv_TransferCity').hide();
        }
        else {
            $('#dv_TransferCity').show();
        }
    }
    function initAirPort(data) {//构建机场选择插件
        var obtOct = $('#td_ObTypeNum :radio:checked').data('Octr');
        var arg = {
            idSeed: 'Dep_AirPort',
            title: '始发',
            titleClass: 'tit2',
            titleIcon: '../static/eth/images/ico_tit_go_red.gif',
            airLineData: data.AirLine,
            airLineFilters: obtOct.D,
            dataIndex: 'D',
            hightClass: 'searchHigh',
            searchInputClass: 'inpt _comm_Ipt',
            searchClass: 'button orbtn2 magn_rig1 search',
            allSelectedClass: 'button orbtn3 magn_rig1 search',
            reverseSelectedClass: 'button orbtn3 magn_rig1 search',
            onFastAirPortSelected: function () {
                fastAirPortSelectedEvent('#dv_DepCity');
            },
            cabinEnabled: true,
            cabinData: data.Cabin == null ? [] : data.Cabin.split(/[\/]/g),
            onFastCabinSelected: function () {
                fastCabinSelectedEvent('#dv_DepCity');
            }
        };
        $('#dv_DepCity').airPortSelect(arg);
        arg.idSeed = 'Tra_AirPort';
        arg.title = '中转';//edit by qiuzhicheng 2015.02.02 GJGD-707 中转城市
        arg.airLineFilters = obtOct.T;
        arg.dataIndex = 'T';//add by qiuzhicheng 2015.02.02 GJGD-707
        arg.titleIcon = '../static/eth/images/ico_tit_add_red.gif';
        arg.onFastAirPortSelected = function () {
            fastAirPortSelectedEvent('#dv_TransferCity');
        };
        arg.onFastCabinSelected = function () {
            fastCabinSelectedEvent('#dv_TransferCity');
        };
        $('#dv_TransferCity').airPortSelect(arg);
        arg.idSeed = 'Arr_AirPort';
        arg.title = '到达 ';//edit by qiuzhicheng 2015.02.02 GJGD-707 到达城市
        arg.airLineFilters = obtOct.A;
        arg.dataIndex = 'A';//add by qiuzhicheng 2015.02.02 GJGD-707
        arg.titleIcon = '../static/eth/images/ico_tit_back_red.gif';
        arg.cabinEnabled = false;
        arg.onFastAirPortSelected = function () {
            fastAirPortSelectedEvent('#dv_ArrCity');
        };
        $('#dv_ArrCity').airPortSelect(arg);
        //console.info('airportInit');
        //$('#td_ObTypeNum :checked').click(); //初始化机场后，根据选择的航班类型控制境内、境外机场显隐

        function fastAirPortSelectedEvent(container) {
            //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
            //var sap = $(container).airPortSelect('', 'getSelectedAirPort');
            //if (sap == '') {
            //    sap = '您还没选择机场';
            //}

            var tip, txt1, txt2 = '';
            var oSelectExcept = $(container).airPortSelect(null, 'getAirPortSelectExceptView');
            if (oSelectExcept.select == '') {
                tip = '您还没选择机场';
            } else {
                tip = '<p style="font-weight:bold;">已选：<br/><div class="selected" style="font-weight:normal;word-break:break-all;">' + oSelectExcept.select + '</div></p>';
                if (oSelectExcept.except != '') {
                    tip += '<p style="font-weight:bold;">排除：<br/><div class="selected" style="font-weight:normal;word-break:break-all;">' + oSelectExcept.except + '</div></p>';
                }
            }
            var dataType = $(container).find('div.tab_lv0').attr('dataType');
            if (dataType == '0') {//境内
                txt1 = '请输入您要快速选择的<font style="font-weight:bold;">机场三字码</font>';
                txt2 = 'PVG/SHA/PEK/';
            }
            else {
                txt1 = '请输入您要快速选择的<font style="font-weight:bold;">国家二字码或机场三字码</font>';
                txt2 = 'US/CA/PVG/SHA/PEK/';
            }
            elB.confirm({
                tle: "快速选择机场",
                msg: '<div style="font-size:10pt;padding:5px;">' + tip
                        + '<div style="color:red;margin-top:5px;">【' + txt1 + '，多个以“/”分隔 如：' + txt2 + '】'
                        + '<textarea id="txt_FastAirPortSelected" style="width:100%;height:150px;"></textarea>一次选择的机场较多，浏览器可能会运行较慢，建议分次操作，一次不超过50个机场！</div></div>',
                width: 600,
                css: 'padding:0;color:#000;',
                buttonList: [{
                    text: "确定",
                    bak: function () {
                        var txt = $.trim($('#txt_FastAirPortSelected').val());
                        if (txt == '') {
                            alert('请输入您想要快速选择的机场');
                        }
                        else {
                            if (txt.substr(txt.length - 1, 1) != '/') {
                                txt += '/';
                            }
                            txt = txt.replace(/\s/g, '').toUpperCase();

                            var countryArray = new Array();
                            var airportArray = new Array();

                            var arr = txt.split('/');

                            if (dataType == '0') {//境内
                                for (var i = 0; i < arr.length; i++) {
                                    if (arr[i] == '') {
                                        continue;
                                    }
                                    if (arr[i].length == 3) {
                                        if (!/^([A-Z]{3})+$/.test(arr[i])) {
                                            alert('请输入正确的机场三字码');
                                            return;
                                        } else {
                                            airportArray.push(arr[i]);
                                        }
                                    } else {
                                        alert('请输入正确的机场三字码');
                                        return;
                                    }
                                }
                            } else {
                                for (var i = 0; i < arr.length; i++) {
                                    if (arr[i] == '') {
                                        continue;
                                    }
                                    if (arr[i].length == 2) {
                                        if (!/^([A-Z]{2})+$/.test(arr[i])) {
                                            alert('请输入正确的国家二字码');
                                            return;
                                        } else {
                                            countryArray.push(arr[i]);
                                        }
                                    } else if (arr[i].length == 3) {
                                        if (!/^([A-Z]{3})+$/.test(arr[i])) {
                                            alert('请输入正确的机场三字码');
                                            return;
                                        } else {
                                            airportArray.push(arr[i]);
                                        }
                                    } else {
                                        alert('请输入正确的国家二字码或机场三字码');
                                        return;
                                    }
                                }
                            }
                            //检测是否有不存在的CODE
                            var dataType = $(container).find('div.tab_lv0').attr('dataType');
                            if (dataType == '0') {//境内
                                for (var i = 0; i < airportArray.length; i++) {
                                    var code = airportArray[i];
                                    var chk = $(container).find('.tab_lv2').find('input:checkbox[value="' + code + '"]');
                                    if (chk.length == 0) {
                                        alert('机场三字码' + code + '不存在!');
                                        return;
                                    }
                                }
                            } else {
                                for (var i = 0; i < countryArray.length; i++) {
                                    var code = countryArray[i];
                                    if (!oGlobalData.country[code]) {
                                        alert('国家二字码' + code + '不存在!');
                                        return;
                                    } else if (dataType == '1' && code == 'CN') {//境外场合排除CN
                                        alert('国家二字码' + code + '不存在!');
                                        return;
                                    }
                                }
                                for (var i = 0; i < airportArray.length; i++) {
                                    var code = airportArray[i];
                                    if (!oGlobalData.airport[code]) {
                                        alert('机场三字码' + code + '不存在!');
                                        return;
                                    } else if (dataType == '1' && oGlobalData.airport[code] == 'CN') {//境外场合排除CN
                                        alert('机场三字码' + code + '不存在!');
                                        return;
                                    }
                                }
                            }

                            $(container).airPortSelect({ 'countryArray': countryArray, 'airportArray': airportArray }, 'fastSearchCountryAirport');
                            elB.hide();

                            //edit by qiuzhicheng 2015.02.02 GJGD-707 end
                        }
                    }
                },
                        {
                            text: "取消",
                            bak: function () { elB.hide(); }
                        }
                ]
            });
        }
        function fastCabinSelectedEvent(container) {
            elB.confirm({
                tle: "快速选择舱位",
                msg: '<div style="font-size:10pt;padding:5px;"><div style="color:red;">【请输入你要快速重选的舱位。多个以“/”分隔 如：A/H/J/】'
                        + '<textarea id="txt_FastCabinSelected" style="width:100%;height:70px;"></textarea></div></div>',
                width: 500,
                css: 'padding:0;color:#000;',
                buttonList: [{
                    text: "确定",
                    bak: function () {
                        var txt = $.trim($('#txt_FastCabinSelected').val());
                        if (txt == '') {
                            alert('请输入您想要快速选择的舱位');
                        }
                        else {
                            if (txt.substr(txt.length - 1, 1) != '/') {
                                txt += '/';
                            }
                            txt = txt.toUpperCase();
                            if (/^([A-Z]\/)+$/.test(txt)) {
                                $(container).airPortSelect(txt, 'selectCabin');
                                elB.hide();
                            }
                            else {
                                alert('请输入正确的舱位编码');
                            }
                        }
                    }
                },
                        {
                            text: "取消",
                            bak: function () { elB.hide(); }
                        }
                ]
            });
        }
    }
    function restDefault() {
        $('#txt_OneSubtracting,#txt_RoundSubtracting,#txt_ChildrenRate,#txt_AirLine,#hd_AirLine,#txt_AlsoApplyAirLine').val('').blur();
        $('#txt_OneSubtracting,#txt_RoundSubtracting,#txt_ChildrenRate').attr('disabled', 'disabled');
        $('#cb_NoOutTicketOffice').removeAttr('checked');
        //add by qiuzhicheng 2015.04.20 GJGD-1293 begin
        setNoOutTicketOffice();
    }
    function fillData() {
    	var policyID = $('#policyId').val()==''? $('#sourcePolicyId').val() : $('#policyId').val();
        if (policyID == '' || !policyID) {
            /*$.ajax({
                url: ajaxUrl + '?method=GetEmptyPolicy',
                type: 'post',
                beforeSend: function (XHR) { },
                success: function (dt, textStatus, jqXHR) {
                    if (typeof dt == 'string' && dt != '') {
                        var data = eval('(' + dt + ')');
                        fillTimeData('Work', data.WorkTime);
                        fillTimeData('WeekEnd', data.WeekEndTime);
                        fillTimeData('Sunday', data.SundayTime);//周日开票时间
                        if (data.ThirdShowPlatform === "ATB") {
                            $("#table_ShowPlatform").show();
                            $("#td_ShowPlatform input:checkbox[value='C']").attr('checked', 'true');
                        }
                    }
                    AfterFillData();

                    var rad = $('input:radio[name="rd_ChangePnr"]:checked').val();
                    var bsp = $('#td_IsCategory input[type="checkbox"]:checked').val();
                    if (bsp != null && bsp != 'A') {
                        $('#IsAutoChangePnrLable').hide();
                        $('#td_NoSetIsEmptyCodeTicket').hide();
                        $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
                        $("#IsAutoChangePnr").removeAttr('checked');
                    }
                    else {
                        if (rad != null && (rad == 'A' || rad == 'C' || rad == 'E')) {
                            $('#IsAutoChangePnrLable').show();
                            $('#td_NoSetIsEmptyCodeTicket').show();
                        }
                        else {
                            $('#IsAutoChangePnrLable').hide();
                            $('#td_NoSetIsEmptyCodeTicket').hide();
                            $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
                            $("#IsAutoChangePnr").removeAttr('checked');
                        }
                    }
                },
                complete: function (XMLHttpRequest, textStatus) {
                    initAllAirPort();
                    if ($("#td_IsCategory").find("input[type='checkbox']:checked").first().val() != 'C'
                      || $("#Sgds").val() == '0') {
                        Hidden();
                    }
                    isLoaded = true;
                    $("input:checkbox[value='O']", $("#td_IsAdapt")).parent().attr('style', 'display:none;');
                }
            });*/
            initAllAirPort();
            TicketPlaceIsShow();
        }
        else {
            /*$.ajax({
                url: ajaxUrl + '?method=GetPolicyData',
                type: 'post',
                data: { id: policyID },
                beforeSend: function (XHR) { },
                success: function (dt, textStatus, jqXHR) {
                    if (typeof dt == 'string' && dt != '') {//数据成功加载，因为后续涉及政策复制功能，此部分还需进行调整
                        $('#dv_ObTypeNum').hide(); //编辑时不允许修改航班类型
                        oldPolicy = dt;
                        var data = eval('(' + dt + ')');
                        objPolicy = data;
                        $("#txt_RefundAddMoney").val(data.Rebate.RefundAddMoney);
                        IsRetreatTicketPolicy(data.Policy.RetreatTicketPolicyID);//判断是否是退票政策。
                        fillTimeData('Work', data.WorkTime);
                        fillTimeData('WeekEnd', data.WeekEndTime);
                        fillTimeData('Sunday', data.SundayTime);//周日开票时间
                        fillTimeData('Rest', data.RestTime);
                        fillTimeData('AutoSpecial', data.AutoSpecialTime);
                        setPolicy(data.Policy);
                        setRebate(data.Rebate, data.Policy, data.RebateEx);
                        setRebateEx(data.RebateEx);
                        TicketPlaceIsShow();
                        //add by qiuzhicheng 2015.04.16 GJGD-1288 begin cb_RoundMustSpace触发过点击事件，可能取消cb_IsReward，为了保持旧数据原样，重新设置
                        if (data.Rebate.IsReward == $('#cb_IsReward').attr('value')) {
                            $('#cb_IsReward').attr('checked', 'checked');
                        }
                        //add by qiuzhicheng 2015.04.16 GJGD-1288 end
                        $('#sp_IsChildren :checked').click();
                        $('#txt_AirLine').val(data.AirLineName);
                        //$('#txt_AirLine').attr('prevValue', data.Policy.AirLine);
                        //initAirPort(eval('(' + data.AirLineData + ')'));
                        setTimeout(function () {//延迟加载机场数据
                            var oldOb = $('#td_ObTypeNum :checked');
                            var newOb = $('#td_ObTypeNum :radio[value=' + copyObTypeNum + ']');
                            var depCity = data.Policy.DepCity;
                            var arrCity = data.Policy.ArrCity;
                            //add by qiuzhicheng 2015.02.02 GJGD-707 begin
                            var depExcept = data.Policy.DepExcept;
                            var arrExcept = data.Policy.ArrExcept;
                            var depCabin = data.Policy.Cabin;
                            var tnsSelect = '';
                            var tnsExcept = '';
                            var tnsCabin = '';
                            var showTrans = false;
                            if (data.Info) {
                                showTrans = true;
                                tnsSelect = data.Info.DepCity;
                                tnsExcept = data.Info.DepExcept;
                                tnsCabin = data.Info.Cabin;
                            }
                            //add by qiuzhicheng 2015.02.02 GJGD-707 end
                            if (newOb.length > 0) {
                                policyID = '';
                                $('#dv_ObTypeNum').show();
                                newOb.attr('checked', 'checked');
                                var oldOctr = oldOb.data('Octr');
                                var newOctr = newOb.data('Octr');
                                ////因为始发地和到达地境内境外永远都只能而且必定存在一种，所以这里做简单判断
                                //if (newOctr.D.toString() == oldOctr.A.toString() && newOctr.A.toString() == oldOctr.D.toString()//出发地、到达地互换
                                //&& oldOctr.D.toString() != oldOctr.A.toString()) {//排除掉境外电子票和境外中转
                                //    depCity = data.Policy.ArrCity;
                                //    arrCity = data.Policy.DepCity;
                                //    //add by qiuzhicheng 2015.02.02 GJGD-707 begin
                                //    depExcept = data.Policy.ArrExcept;
                                //    arrExcept = data.Policy.DepExcept;
                                //    //add by qiuzhicheng 2015.02.02 GJGD-707 end
                                //}
                                //add by qiuzhicheng 2015.02.02 GJGD-707 begin
                                var reverse = false;
                                if (newOctr.D == oldOctr.D && newOctr.A == oldOctr.A) {
                                    //新旧类型一致 默认赋值
                                } else if (newOctr.D == oldOctr.A && newOctr.A == oldOctr.D) {
                                    //始发，到达反转
                                    reverse = true;
                                    depCity = data.Policy.ArrCity;
                                    depExcept = data.Policy.ArrExcept;
                                    arrCity = data.Policy.DepCity;
                                    arrExcept = data.Policy.DepExcept;
                                } else {
                                    //不能直接匹配的情况
                                    if (newOctr.D != oldOctr.D) {
                                        if (oldOctr.D != '2' && newOctr.D == '2') {//境内，境外可以转成全球 changeCopySelect未写!
                                            depCity = changeCopySelect(oldOctr.D, data.Policy.DepCity, data.Policy.DepExcept);
                                            depExcept = changeCopyExcept(oldOctr.D, data.Policy.DepCity, data.Policy.DepExcept);
                                        } else {
                                            //始发不同，清空始发
                                            depCity = '';
                                            depExcept = '';
                                        }
                                        //清空始发舱位
                                        depCabin = '';
                                    }
                                    if (newOctr.A != oldOctr.A) {
                                        if (oldOctr.A != '2' && newOctr.A == '2') {//境内，境外可以转成全球 changeCopySelect未写!
                                            arrCity = changeCopySelect(oldOctr.A, data.Policy.ArrCity, data.Policy.ArrExcept);
                                            arrExcept = changeCopyExcept(oldOctr.A, data.Policy.ArrCity, data.Policy.ArrExcept);
                                        } else {
                                            //到达不同，清空始发
                                            arrCity = '';
                                            arrExcept = '';
                                        }
                                    }
                                }
                                //有中转
                                showTrans = newOctr.T != '' ? true : false;
                                if (data.Info && showTrans) {
                                    if (newOctr.T == oldOctr.T) {
                                        //新旧类型一致 默认赋值
                                    } else {
                                        //不能直接匹配的情况
                                        if (oldOctr.T != '2' && newOctr.T == '2') {//境内，境外可以转成全球 changeCopySelect未写!
                                            tnsSelect = changeCopySelect(oldOctr.T, data.Info.DepCity, data.Info.DepExcept);
                                            tnsExcept = changeCopyExcept(oldOctr.T, data.Info.DepCity, data.Info.DepExcept);
                                        } else {
                                            tnsSelect = '';
                                            tnsExcept = '';
                                        }
                                        //清空中转舱位
                                        tnsCabin = '';
                                    }
                                }
                                //始发到达反转时，若新旧都有中转舱位，则始发到达中转舱位反转
                                if (reverse && newOctr.T != '' && oldOctr.T != '') {
                                    depCabin = data.Info.Cabin;
                                    tnsCabin = data.Policy.Cabin;
                                }
                                //add by qiuzhicheng 2015.02.02 GJGD-707 begin
                            }
                            //console.info('loaded');
                            initAllAirPort();
                            //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
                            //$('#dv_DepCity').airPortSelect(depCity, 'selectAirPort');
                            //$('#dv_DepCity').airPortSelect(data.Policy.Cabin, 'selectCabin');
                            //if (data.Info) {
                            //    $('#dv_TransferCity').airPortSelect(data.Info.DepCity, 'selectAirPort');
                            //    $('#dv_TransferCity').airPortSelect(data.Info.Cabin, 'selectCabin');
                            //}
                            //$('#dv_ArrCity').airPortSelect(arrCity, 'selectAirPort');

                            var depSelectExcept = { 'select': depCity, 'except': depExcept };
                            var tnsSelectExcept = { 'select': tnsSelect, 'except': tnsExcept };
                            var arrSelectExcept = { 'select': arrCity, 'except': arrExcept };

                            $('#dv_DepCity').airPortSelect(depSelectExcept, 'initAirPortSelectExcept');
                            $('#dv_DepCity').airPortSelect(depCabin, 'selectCabin');
                            if (showTrans) {
                                $('#dv_TransferCity').airPortSelect(tnsSelectExcept, 'initAirPortSelectExcept');
                                $('#dv_TransferCity').airPortSelect(tnsCabin, 'selectCabin');
                            }
                            $('#dv_ArrCity').airPortSelect(arrSelectExcept, 'initAirPortSelectExcept');
                            //edit by qiuzhicheng 2015.02.02 GJGD-707 end
                            $('#td_ObTypeNum :checked').click();
                        }, 50);
                        setUnApplyTime('#td_UnApplyTimeS', data.UnApplyTimeS);
                        setUnApplyTime('#td_UnApplyTimeE', data.UnApplyTimeE);
                        simpleTextFill('D', data);
                        setCheckBoxClick('#cb_ApplyFlightG', data.ApplyFlightG != '');
                        setCheckBoxClick('#cb_ApplyFlightR', data.ApplyFlightR != '');
                        setCheckBoxClick('#cb_UnApplyFlight', data.UnApplyFlight != '');
                        //这里先设置Tour Code本身的值，然后再去检测之前不适用里面的值，如果反过来不适用里面的不会检测
                        setCheckBoxClick('#cb_TourCodeInclude', data.Rebate.TourCodeInclude != '');
                        if (data.RebateEx.TourCode != '') {
                            setCheckBoxClick('#cb_TourCodeInclude', true);
                            $("#txt_TourCodeInclude").val(data.RebateEx.TourCode);
                            $("#cb_TourCodeNoAgentFee").attr("checked", "checked");
                            $("#cb_TourCodeNoReward").attr("checked", "checked");
                        }
                        if (data.Policy.ObTypeNum == '0110' || data.Policy.ObTypeNum == '0101') {
                            //GJJSZC-498 2015-1-6 modify by lihui
                            $("input:checkbox[value='V']", $("#td_IsAdapt")).removeAttr("checked");
                            $("input:checkbox[value='V']", $("#td_IsAdapt")).attr("disabled", "disabled");
                        }
                        //是否隐藏不适用选项中的“共享航班代码”
                        //在添加中隐藏该选项，在修改中，如果不适用中没有勾选“共享航班代码”，则也隐藏该选项
                        if (data.Rebate.IsAdapt.indexOf('O') < 0) {
                            $("input:checkbox[value='O']", $("#td_IsAdapt")).parent().attr('style', 'display:none;');
                        }

                        if (data.Policy.FlightType.indexOf("1") >= 0) {
                            $(".td_DurationDay").show();
                        } else {
                            $(".td_DurationDay").hide();
                        }

                        if (data.Rebate.LuggageAllowance == "-1") {
                            $("#txt_LuggageAllowanceValue").val("");
                        }

                        if (data.RebateEx.ShareFlightDiscount == "-1") {
                            $("#txt_ShareFlightDiscount").val("");
                        }

                        //GJJSZC-474 2014-12-18 add by lihui 显示录入格式提示
                        $(':text[data-empty]').emptyValue();

                        if (copyObTypeNum != '')
                            data.IsEdit = true;
                        if (!data.IsEdit) {
                            $("#btn_Save").val("关闭");
                            $("#btn_Save").off("click").click(function () {
                                parent.AppMy.hide();
                            });

                        }
                    }
                    else {
                        policyID = '';
                        initAllAirPort();
                    }
                    AfterFillData();

                    //GJGD-4587 政策前台判断自动换编与无编是否接受空编显示与否
                    var rad = $('input:radio[name="rd_ChangePnr"]:checked').val();
                    var bsp = $('#td_IsCategory input[type="checkbox"]:checked').val();
                    if (bsp != null && bsp != 'A') {
                        $('#IsAutoChangePnrLable').hide();
                        $('#td_NoSetIsEmptyCodeTicket').hide();
                        $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
                        $("#IsAutoChangePnr").removeAttr('checked');
                    }
                    else {
                        if (rad != null && (rad == 'A' || rad == 'C' || rad == 'E')) {
                            $('#IsAutoChangePnrLable').show();
                            $('#td_NoSetIsEmptyCodeTicket').show();
                        }
                        else {
                            $('#IsAutoChangePnrLable').hide();
                            $('#td_NoSetIsEmptyCodeTicket').hide();
                            $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
                            $("#IsAutoChangePnr").removeAttr('checked');
                        }
                    }
                    //GJGD-4587 政策前台判断自动换编与无编是否接受空编显示与否

                    //GJGD-4701 政策新增GDS换编选项（判断GDS换编选项显示与否）
                    //if (data.Rebate.IsCategory == 'C' && (data.Rebate.GdsCode == '2' || data.Rebate.GdsCode == '3' || data.Rebate.GdsCode == '4')) {
                    //    $('#hsGDSChange').show();
                    //    $('#hsOLDChange').hide();
                    //}
                    //else {
                    //    $('#hsGDSChange').hide();
                    //    $('#hsOLDChange').show();
                    //}
                    //GJGD-4701 政策新增GDS换编选项（判断GDS换编选项显示与否）
                },
                complete: function (XMLHttpRequest, textStatus) {

                    if ($("#td_IsCategory").find("input[type='checkbox']:checked").first().val() != 'C'
                      || $("#Sgds").val() == '0') {
                        Hidden();
                    };
                    isLoaded = true;
                }
            });*/
        	initAllAirPort();
        	resumeCheck1($('#rd_ObTypeNum').val(), 'rd_ObTypeNum');
        $('#td_ObTypeNum :checked').click();
        	var depCity = $('#departure').val();
            var arrCity = $('#arrival').val();
            var depExcept = $('#departureExclude').val();
            var arrExcept = $('#arrivalExclude').val();
            var depCabin = $('#departureCabins').val();
            var tnsSelect = $('#transfer').val();
            var tnsExcept = $('#transferExclude').val();
            var tnsCabin = $('#arrivalCabins').val();
            var showTrans = false;
            if (tnsSelect) {
                showTrans = true;
            }
            var depSelectExcept = { 'select': depCity, 'except': depExcept };
            var tnsSelectExcept = { 'select': tnsSelect, 'except': tnsExcept };
            var arrSelectExcept = { 'select': arrCity, 'except': arrExcept };

            $('#dv_DepCity').airPortSelect(depSelectExcept, 'initAirPortSelectExcept');
            $('#dv_DepCity').airPortSelect(depCabin, 'selectCabin');
            if (showTrans) {
                $('#dv_TransferCity').airPortSelect(tnsSelectExcept, 'initAirPortSelectExcept');
                $('#dv_TransferCity').airPortSelect(tnsCabin, 'selectCabin');
            }
            $('#dv_ArrCity').airPortSelect(arrSelectExcept, 'initAirPortSelectExcept');
            
        }
    }
    function resumeCheck1(values, name) {
    	    if (!values){
    	    	return;
    	    }
	    	var checkAll = $("input[name='" + name + "']");
	    	$.each(checkAll, function(j, check) {
	    		var checkValue = $(check).val();
	    		if (values.indexOf(checkValue) >= 0) {
	    			$(check).iCheck('check');
	    			$(check).parent().addClass("checked");
	    		} else {
	    			$(check).iCheck('uncheck');
	    			$(check).parent().removeClass("checked");
	    		}
	    	});
    }
    function IsRetreatTicketPolicy(retreatPolicyID) {
        if (retreatPolicyID == '0' || retreatPolicyID == null || retreatPolicyID == undefined) {
            $("#RetreatTicket").hide();
            document.getElementById("txt_RetreatTicketDiscount").disabled = true;

        }
        else {
            $("#RetreatTicket").show();
            $("#txt_RetreatTicketDiscount").show();
            document.getElementById("txt_RetreatTicketDiscount").disabled = false;
            $("#cb_Isguarantees").attr("checked", "checked");
        }
    }
    function AfterFillData() {//数据填充完毕后，设置控件之间的业务关联
        setIsChildren();
        setShareFlight();
        setMustProviderReviewDisabled();
        setRoundMustSpaceDisabled();
        setTicketPlaceRateHint();
    }
    function fillTimeData(key, time) {//填充上下班时间，H代表Hour,M代表Minute,S代表Start，E代表End
        var eb = false;
        if (time && time != '' && time != '-') {
            var arr = time.split(/[\:\-]/g);
            if (arr.length == 4) {
                eb = true;
                $.each(arr, function (i, n) {
                    var sel = '#sel_' + key + 'Time';
                    switch (i) {
                        case 0:
                            sel += 'HS';
                            break;
                        case 1:
                            sel += 'MS';
                            break;
                        case 2:
                            sel += 'HE';
                            break;
                        default:
                            sel += 'ME';
                            break;
                    }
                    if ((n + '').length == 1) {
                        n = '0' + n;
                    }
                    $(sel).val(n);
                });
            }
        }
        setTimeEnabled(eb);
        function setTimeEnabled(enabled) {
            if ($('#cb_' + key).length > 0) {
                $('#cb_' + key)[0].checked = !enabled;
                C.Dom.setDisabled($('#cb_' + key).parent().parent().parent().find('select'), enabled, true);
            }
        }
    }

});

//GJGD-3525 add by lihui 2016-6-3
function setTourCodeRemarkDisplay() {
    if ($("#cb_IsAuto").attr("checked") == "checked" && "2/3/4".indexOf($("#Sgds").val()) > -1 && isExtProvider) {
        $(".TourCodeRemark").show();
    }
    else { $(".TourCodeRemark").hide(); }
}

function fileThreeAuto(type, AgentCode) {
    if ($("input:checkbox[name='cb_IsThreeAgreement']:checked") != null) {
        if (type == '' || type == undefined) {
            alert('请选择大客户协议类型');
            return;
        }
        var airLine = $("#hd_AirLine").val();
        if (airLine == "") {
            alert("请先选择航空公司");
            $("#cb_IsThreeAgreement").removeAttr("checked");
            return;
        }

        var office = $("#txt_TicketOffice").val();

        //GJGD-4559 判断是否为独立系统
        var istrue = 1;
        if ($('#table_ShowPlatform').css('display') == 'none') {
            istrue = 0;
        }
        //GJGD-4559 判断是否为独立系统

        $.ajax({
            url: ajaxUrl + '?method=GetETermThreeAuto',
            data: { AirLine: airLine, Type: type, Office: office, istrue: istrue },
            type: 'post',
            dataType: 'text',
            success: function (dt, textStatus, jqXHR) {
                var options = "";
                options += "<option value=''></option>";
                if (dt != "") {
                    var dts = dt.split(',');

                    for (var i = 0; i < dts.length; i++) {
                        options += "<option value='" + dts[i] + "'>" + dts[i] + "</option>";
                    }
                    $("#sl_AgentCode").html(options).removeAttr("disabled");
                    if (AgentCode != undefined) {
                        $("#sl_AgentCode").val(AgentCode);
                    }
                } else {
                    alert("Eterm中没有对应大客户编号，请先去Eterm中配置！");
                    $("input:checkbox[name='cb_IsThreeAgreement']").removeAttr('checked');

                    $("#sl_AgentCode").html(options).removeAttr("disabled");
                }
            }
        });
    }
}
function changeTxtPriceTip() {
    var value = $("#drpLstPrice").val();
    var obj = $("#txt_Price");
    var txtValue = obj.val();
    var emptyValue = obj.attr("data-empty");
    var tipOne = "指定金额以上才开票，比如：2000";
    var tipTwo = "指定金额以下才开票，比如：5000";
    if (value == 0) {
        obj.attr("data-empty", tipOne);
        if (obj.val2() == ""
            || (obj.val2() != tipOne && obj.val2() == tipTwo)
            ) {
            obj.val2(tipOne);
        }
    }
    else {
        obj.attr("data-empty", tipTwo);
        if (obj.val2() == ""
            || (obj.val2() != tipTwo && obj.val2() == tipOne)
            ) {
            //$("#txt_Price").val($("#txt_Price").attr("data-empty"));
            obj.val2(tipTwo);
        }
    }
    obj.emptyValue();
}

//chekbox group 单选
function ticketPostponed(name) {
    $(':checkbox[name=' + name + ']').each(function () {
        $(this).click(function () {
            if ($(this).attr('checked')) {
                $(':checkbox[name=' + name + ']').removeAttr('checked');
                $(this).attr('checked', 'checked');
                if (name == 'cb_RefundGrade') {
                    if ($(this).attr('child') == 'ok') {
                        $(".GJGD-4079-times").show();
                    } else {
                        $(".GJGD-4079-times").hide();
                        $(":checkbox[name=cb_RescheduledGrade]").removeAttr('checked');
                        $(":checkbox[name=cb_DrawerTicket]").removeAttr('checked');
                    }
                }
            } else {
                if (name == 'cb_RefundGrade') {
                    $(".GJGD-4079-times").hide();
                    $(":checkbox[name=cb_RescheduledGrade]").removeAttr('checked');
                    $(":checkbox[name=cb_DrawerTicket]").removeAttr('checked');
                }
            }
        });
    });
}

//必须选择一个
function ticketPostponed2(name) {
    var chbox = $(':checkbox[name=' + name + ']');
    $(':checkbox[name=' + name + ']').each(function () {
        $(this).click(function () {
            if (!$(this).attr('checked')) {
                chbox.attr('checked', true);
                $(this).removeAttr('checked');
            }
        });
    });
}


function setPolicy(policy) {
    complexCheckBoxFill('P', policy);
    simpleTextFill('P', policy);
    simpleRadioFill('P', policy);
}
function setRebate(rebate, policy, rebatex) {
    if (rebate) {
        complexCheckBoxFill('R', rebate);
        simpleTextFill('R', rebate);
        simpleRadioFill('R', rebate);
        simpleCheckBoxFill('R', rebate);
        simpleCheckBoxByNameFill('R', rebate);
        setCheckBoxClick('#cb_IsAuto', rebate.IsAuto);

        if (rebate.IsAuto > 0 && rebate.IsCategory == 'A' && policy.TicketOffice.length > 0) {
            BspAutoTicketIsChecked(rebate.IsCategory, policy.TicketOffice, true);
        }
        //setCheckBoxClick('#cb_IsAutoRefund', rebate.IsAutoRefund);
        setCheckBoxClick('#cb_Price', rebate.Price > 0 || rebate.PriceEnd > 0);
        //setCheckBoxClick('#cb_AgentCode', rebate.AgentCode != '');
        setCheckBoxClick('#cb_AutoAgent', rebate.AutoAgent >= 0);
        if (rebate.AutoAgent < 0) {
            $("#txt_AutoAgent").val("");
        }

        $("#drpLstPrice").val(rebate.IsPriceHigher.toLowerCase() == "true" ? "1" : "0");
        //GJGD-1169  2015-04-02 add by dsp
        $("#txt_ParValue").val(rebate.ParValue >= 0 ? rebate.ParValue : "");
        $('#sp_IsParValueType :radio[value=' + (rebate.ParValueType == false ? "0" : "1") + ']').attr("checked", "checked");
        setCheckBoxClick('#cb_ParValue', rebate.ParValue >= 0);
        //GJGD-1169
        //changeTxtPriceTip();
        if (rebate.IsCategory == "C") {
            $("#hidgds").show();
            if (rebate.IsItinerary != null && rebate.IsItinerary != "0") {
                $("#Itinerary").val(rebate.IsItinerary);
            }
            if (rebate.GdsCode != null && rebate.GdsCode.length > 0 && rebate.GdsCode != "0") {
                $("#Sgds").val(rebate.GdsCode);
                setTourCodeRemarkDisplay();
            }

            //GJGD-4118
            $(".GJGD-4079").show();
        }
        //add by qiuzhicheng 20150514 GJGD-1420 begin
        $('#hid_PolicyGroup').val(rebate.PolicyGroup == '0' ? '' : rebate.PolicyGroup);
        $('#txt_PolicyGroup').val(rebate.PolicyGroup == '0' ? '' : rebate.PolicyGroup);
        //add by qiuzhicheng 20150514 GJGD-1420 end
        //AutoChangePnrSet();
        if (rebate.IsAutoChangePnr == "1")
            $("#IsAutoChangePnr").attr("checked", true);
        else
            $("#IsAutoChangePnr").attr("checked", false);

        if (rebate.IsAuto == 1 && rebate.IsThreeAgreement > 0) {
            $("input:checkbox[name='cb_IsThreeAgreement'][value=" + rebate.IsThreeAgreement + "]").attr('checked', 'checked')
            fileThreeAuto(rebate.IsThreeAgreement, rebate.AgentCode);
        }

        //展示平台页面呈现
        if (rebate.IsOEM === 2) {
            $("#table_ShowPlatform").show();
            if (rebatex.ShowPlatform != "C") {
                complexCheckBoxFill('RE', rebatex);
            } else {
                $("#td_ShowPlatform input:checkbox[value='C']").attr('checked', 'true');
            }
        }




    }
}
function setRebateEx(rebateEx) {
    if (rebateEx) {
        setCheckBoxClick('#cb_FareBasisCodeInclude', rebateEx.FareBasisCodeInclude != '');
        //setcheckboxclick('#rd_farebasiscodeincludenoclose', rebateex.farebasiscodeincludenoclose > 0);
        setCheckBoxClick('#cb_ApplicableFreightBase', rebateEx.ApplicableFreightBase != '');
        simpleTextFill('RE', rebateEx);
        simpleRadioFill('RE', rebateEx);
        simpleCheckBoxFill('RE', rebateEx);
        setCheckBoxClick('#cb_ChildrenFee', rebateEx.ChildrenFee > 0);
        setCheckBoxClick('#cb_ShareFlightDiscount', rebateEx.ShareFlightDiscount >= 0);
        setCheckBoxClick('#cb_BabyFee', rebateEx.BabyFee > 0);
        setCheckBoxClick('#cb_NoOutTicketOffice', rebateEx.NoOutTicketOffice != '');
        setCheckBoxClick('#cb_RoundMustSpace', rebateEx.RoundMustSpace != '');
        setCheckBoxClick('#cb_NotApplicableAirLine', rebateEx.NotApplicableAirLine != '');
        setCheckBoxClick('#cb_ITPriceMoreAddFee', rebateEx.ITPriceMoreAddFee > 0);
        setCheckBoxClick('#cb_TourCode', rebateEx.TourCode != '');
        //GJGD-1024 2015-3-4 add by lihui
        if (rebateEx.TourCode != "") {
            if (rebateEx.TourCode.length > 1) {
                setTimeout(function () {
                    //$("input[name='rd_TourCode']")[1].click();
                    $("#txt_TourCodeLong").val(rebateEx.TourCode);
                    $("#txt_TourCodeLong").removeClass("gray");
                }, 500);
            }
            //else {
            //    setTimeout(function () {
            //        $("input[name='rd_TourCode']")[0].click();
            //        $("#txt_TourCode").val(rebateEx.TourCode);
            //        $("#txt_TourCode").removeClass("gray");
            //    }, 500);
            //}
        }
        //GJGD-1024 end
        setCheckBoxClick('#cb_TransitAirport', rebateEx.TransitAirport != '');
        //del by qiuzhicheng 2015.04.20 GJGD-1293 begin
        //C.Dom.setDisplay($("#txt_NoOutTicketOfficeBack"), rebateEx.NoOutTicketOfficeBack != '');
        //del by qiuzhicheng 2015.04.20 GJGD-1293 end
        //add by qiuzhicheng 2015.04.20 GJGD-1293 begin
        setNoOutTicketOffice();
        //add by qiuzhicheng 2015.04.20 GJGD-1293 end


    }
}
function setUnApplyTime(selector, times) {
    if (times && times != '') {
        var arr = new Array();
        var tmpArr = times.split(/[~;]/g);
        for (var i = 0; i < tmpArr.length; i += 2) {
            arr.push({ Start: C.Parse.parseDate(tmpArr[i]), End: C.Parse.parseDate(tmpArr[i + 1]) });
        }
        $(selector).dateRange(arr, 'setValue');
    }
}
function setCheckBoxClick(selector, checked) {
    if (checked) {
        $(selector).attr('checked', 'checked').click().attr('checked', 'checked');
    }
    else {
        $(selector).removeAttr('checked');
    }
}
function simpleTextFill(code, data) {//输入框简单填充
    $('[fm=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'id');
        //edit by qiuzhicheng 20170527 GJGD-1794 begin
        //$(n).val(data[key] != $(n).attr('data-remove') ? data[key] : '').blur();

        if (code == "RE" && key == "ShareFlightOnlyApply") {
            if (data[key].length > 0) {//这里比较的的是字符串长度
                $(n).val(data[key]);
                $("#cb_ShareFlightOnlyApply").attr('checked', 'checked');
            }
        }

        $(n).val(data[key] != $(n).attr('data-remove') ? data[key] : '').filter(function () {
            //加载数据时，跳过供应商OFFICE号和开票OFFICE号的验证
            if ($(this).attr('id') == 'txt_OrdinaryOffice' || $(this).attr('id') == 'txt_TicketOffice') {
                return false;
            } else {
                return true;
            }
        }).blur();
        //edit by qiuzhicheng 20170527 GJGD-1794 end
    });
}
function getKey(selector, att) {
    var key = $(selector).attr(att);
    return key.substr(key.indexOf('_') + 1);
}
function simpleRadioFill(code, data) {//单选框简单填充
    $('[rd=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'id');
        //共享航班 指定奖励 赋值
        if (code == "RE" && key == "ShareflightMade") {
            if (data[key] == "B") {
                $("#txt_ShareFlightReward_B").val(data["ShareFlightReward"]);
            } else if (data[key] == "D") {
                $("#txt_ShareFlightReward_D").val(data["ShareFlightReward"]);
            }
        }
        $(':radio[value=' + data[key] + ']', n).attr("checked", "checked");
        $(':radio[value=' + data[key] + ']', n).click();
    });
}
function simpleCheckBoxFill(code, data) {//复选框简单填充
    $('[cb=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'id');
        if ($(n).val() == data[key]) {
            $(n).attr('checked', 'checked');
        }
        else {
            $(n).removeAttr('checked', 'checked');
        }
    });
}
function simpleCheckBoxByNameFill(code, data) {
    $('[cbn=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'name');
        var name = 'cb_' + key;
        $(':checkbox[name=' + name + ']').each(function (i, n) {
            if ($(this).val() == data[key]) {
                $(this).attr('checked', 'checked');
                if (key == 'RefundGrade' && $(this).val() == 2) {
                    $(".GJGD-4079-times").show();
                }
            } else {
                $(this).removeAttr('checked', 'checked');
            }
        });
    });
}
function complexCheckBoxFill(code, data) {//复选框复杂填充
    $('[cbx=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'id');
        $(':checkbox:not[value!=""]', n).each(function (j, m) {
            if (data[key].toString().indexOf($(m).val()) > -1) {
                $(m).attr('checked', 'checked');
                if ($(n).attr('cbxc')) {//如果存在特定attr，说明当该复选框被选定时，需要执行click事件
                    $(m).click().attr('checked', 'checked');
                }
            }
            else {
                $(m).removeAttr('checked', 'checked');
            }
        });
    });
}
function btnSave_click() {
    if (copyObTypeNum != '') {
        objPolicy.Policy.PID = 0;
        //GJGD-1120 2015-3-17 add by lihui
        objPolicy.Policy.ManagerRemark = '';
        objPolicy.Rebate.Remarks = '';
        objPolicy.Rebate.IsMatic = 0;
        //GJGD-1120 end 
    }
    if (objPolicy == null) {
        isAdd = true;
        objPolicy = {};
        objPolicy.Policy = {}; //政策主表
        objPolicy.Policy.PID = 0;
        objPolicy.Rebate = {}; //备注表
        objPolicy.RebateEx = {}; //扩展备注表
        objPolicy.Info = {}; //中转表
    }

    //Policy
    simpleTextJsonFill('P', objPolicy.Policy);
    simpleRadioJsonFill('P', objPolicy.Policy);
    complexCheckBoxJsonFill('P', objPolicy.Policy, '/');
    //GJJSZC-501 添加政策类型选择校验，航司校验
    if (objPolicy.Policy.AirLine == '') {
        alert("航司不存在，请重新选择航司！")
        return;
    }
    //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
    //objPolicy.Policy.DepCity = $("#dv_DepCity").airPortSelect(null, "getSelectedAirPort");
    var airportDep = $("#dv_DepCity").airPortSelect(null, "getAirPortSelectExcept");
    objPolicy.Policy.DepCity = airportDep.select;
    //edit by qiuzhicheng 2015.02.02 GJGD-707 end
    if (objPolicy.Policy.DepCity == '') {
        alert("请选择出发地！");//edit by qiuzhicheng 2015.02.02 GJGD-707
        return;
    }
    else if (!checkAirprtMaxLength(objPolicy.Policy.DepCity, '始发', 'select')) {
        return;
    }
    //add by qiuzhicheng 2015.02.02 GJGD-707 begin
    objPolicy.Policy.DepExcept = airportDep.except;
    if (!checkAirprtMaxLength(objPolicy.Policy.DepExcept, '始发', 'except')) {
        return;
    }
    //add by qiuzhicheng 2015.02.02 GJGD-707 end
    objPolicy.Policy.Cabin = $("#dv_DepCity").airPortSelect(null, "getSelectedCabin");
    if (objPolicy.Policy.Cabin == '') {
        alert("请选择出发舱位！");//edit by qiuzhicheng 2015.02.02 GJGD-707
        return;
    }

    objPolicy.Policy.Provider = curUser;
    //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
    //objPolicy.Policy.ArrCity = $("#dv_ArrCity").airPortSelect(null, "getSelectedAirPort");
    var airportArr = $("#dv_ArrCity").airPortSelect(null, "getAirPortSelectExcept");
    objPolicy.Policy.ArrCity = airportArr.select;
    //edit by qiuzhicheng 2015.02.02 GJGD-707 end
    if (objPolicy.Policy.ArrCity == '') {
        alert("请选择到达地！");//edit by qiuzhicheng 2015.02.02 GJGD-707
        return;
    }
    else if (!checkAirprtMaxLength(objPolicy.Policy.ArrCity, '到达', 'select')) {
        return;
    }
    //add by qiuzhicheng 2015.02.02 GJGD-707 begin
    objPolicy.Policy.ArrExcept = airportArr.except;
    if (!checkAirprtMaxLength(objPolicy.Policy.ArrExcept, '到达', 'except')) {
        return;
    }
    //add by qiuzhicheng 2015.02.02 GJGD-707 end
    objPolicy.Policy.UpdateUser = curUser;
    var isguarantees = $("#cb_Isguarantees").is(":checked") ? "2" : "0";
    var refundAddMoney = $("#txt_RefundAddMoney").val();
    //Rebate
    complexCheckBoxJsonFill('R', objPolicy.Rebate, ',');
    simpleTextJsonFill('R', objPolicy.Rebate);
    simpleRadioJsonFill('R', objPolicy.Rebate);
    simpleCheckBoxJsonFill('R', objPolicy.Rebate);

    //GJGD-4118
    simpleCheckBoxJsonByNameFill('R', objPolicy.Rebate);

    //添加选择的运价限制 0:票面(不含税)高于,1:票面(不含税)低于
    objPolicy.Rebate["IsPriceHigher"] = $("#drpLstPrice").val();
    //GJGD-1169  2015-04-02 add by dsp
    //add by qiuzhicheng 20150511 GJGD-1420 begin
    objPolicy.Rebate.PolicyGroup = $('#hid_PolicyGroup').val() == '' ? '0' : $('#hid_PolicyGroup').val();
    //add by qiuzhicheng 20150511 GJGD-1420 end
    objPolicy.Rebate["IsAuto"] = $("#cb_IsAuto").is(':checked');
    //alert("r_isauto" + objPolicy.Rebate["IsAuto"]);
    //alert("c_parvalue" + $("#cb_ParValue")[0].checked);
    if (objPolicy.Rebate["IsAuto"] == 0 || $("#cb_ParValue")[0].checked == false) {
        objPolicy.Rebate["ParValue"] = -1;
    }
    else {
        objPolicy.Rebate["ParValue"] = $("#txt_ParValue").val() == "" ? -1 : $("#txt_ParValue").val();
    }
    //if (objPolicy.Rebate["IsAuto"] == 0) {
    //    objPolicy.Rebate["IsThreeAgreement"] = 0;
    //} else {
    //    objPolicy.Rebate["IsThreeAgreement"] = $('input:radio[name=rd_IsThreeAgreement]:checked').val() == "1" ? 1 : 2;
    //}
    objPolicy.Rebate["ParValueType"] = $('input:radio[name=rd_ParValueType]:checked').val() == "0" ? 0 : 1;
    //GJGD-1169
    //add by wangshuang on 2014-12-27 --start  伽利略
    if (objPolicy.Rebate.IsCategory == "C") {
        //add by zh 20150602 GJGD-1508 BEGIN
        //if ($("#Itinerary").val()=="0") {
        //    $("#Itinerary").focus();
        //    alert('请您选择是否可提供行程单');
        //    return;
        //}
        //ADD BY ZH 20150602 GJGD-1508 END
        //add by qiuzhicheng 2015.04.22 GJGD-1262 begin
        if (isExtProvider) {
            if ($("#Sgds").val() == '0') {
                $("#Sgds").focus();
                alert('请您选择开票GDS');
                return;
            }
        }

        if ((isExtProvider || (!isExtProvider && IsAddEtermConfigSupply)) && $("#Sgds").val() != '0' && $("#Sgds").val() != '5') {
            //Add by zhengbo 2015-9-8 GJGD-2044
            if ($("#txt_TicketPlace").val() == "") {
                $("#txt_TicketPlace").focus();
                alert("请选择开票地");
                return;
            } else {
                //验证机场二字码是否存在

                var isNoExist = false;
                $.ajax({
                    type: "POST",
                    url: ajaxUrl + "?method=ValidCountryCode",
                    async: false,//这里必须同步操作，否则就会和save同时操作
                    data: { TicketPlace: $("#txt_TicketPlace").val() },
                    success: function (data) {
                        if (data == 0) {
                            isNoExist = true;
                        }
                    }
                });

                if (isNoExist) {
                    alert("您输入的国家地区或者城市的编码不存在!");
                    $("#txt_TicketPlace").focus();
                    return;
                }
            }
        }

        //End GJGD-2044

        objPolicy.Rebate.IsItinerary = $("#Itinerary").val();
        //add by qiuzhicheng 2015.04.22 GJGD-1262 end
        objPolicy.Rebate.GdsCode = $("#Sgds").val();

        //GJGD-4118
        if (!$(":checkbox[name=cb_RefundGrade]").is(":checked")) {
            alert("请勾选出票改期选项!");
            $(":checkbox[name=cb_RefundGrade]").addClass("err").focus();
            return;
        }

        if (objPolicy.Rebate.RefundGrade == 2 && (!$(":checkbox[name=cb_RescheduledGrade]").is(":checked") || !$(":checkbox[name=cb_DrawerTicket]").is(":checked") || !$(":checkbox[name=cb_LimitTicketDate]").is(":checked"))) {
            alert("请勾选出票改期有时差子项和出票时限选项!");
            if (!$(":checkbox[name=cb_DrawerTicket]").is(":checked"))
                $(":checkbox[name=cb_DrawerTicket]").addClass("err").focus();
            else if (!$(":checkbox[name=cb_RescheduledGrade]").is(":checked"))
                $(":checkbox[name=cb_RescheduledGrade]").addClass("err").focus();
            else if (!$(":checkbox[name=cb_LimitTicketDate]").is(":checked"))
                $(":checkbox[name=cb_LimitTicketDate]").addClass("err").focus();

            return;
        }

        if (!$(":checkbox[name=cb_IsHolidaySales]").is(":checked")) {
            alert("请选择节假日是否可售后!");
            $(":checkbox[name=cb_IsHolidaySales]").addClass("err").focus();
            return;
        }
    } else {
        objPolicy.Rebate.IsItinerary = "0";
        objPolicy.Rebate.GdsCode = "0";
        $("#txt_TicketPlace").val("");
        objPolicy.Rebate.TicketPlace = "";

    }
    //add by wangshuang on 2014-12-27 --end  伽利略
    //add by qiuzhicheng 2015.04.02 GJGD-1207 begin
    if (!objPolicy.Rebate.ProtocolType) {
        objPolicy.Rebate.ProtocolType = '0';
    }
    if (objPolicy.Rebate.ProtocolType != '2') {
        objPolicy.Rebate.Protocol = '';
    }
    objPolicy.Rebate.IsAutoChangePnr = 0;
    //if (AutoChangePnrSet() && $("#IsAutoChangePnr").is(':checked'))
    //    objPolicy.Rebate.IsAutoChangePnr = 1;
    if ($("#IsAutoChangePnr").is(':checked'))
        objPolicy.Rebate.IsAutoChangePnr = 1;

    //add by qiuzhicheng 2015.04.02 GJGD-1207 end
    //RebateEx
    simpleTextJsonFill('RE', objPolicy.RebateEx);
    simpleRadioJsonFill('RE', objPolicy.RebateEx);
    simpleCheckBoxJsonFill('RE', objPolicy.RebateEx);
    complexCheckBoxJsonFill('RE', objPolicy.RebateEx, ",");
    //GJGD-1024 2015-3-4 add by lihui
    objPolicy.RebateEx.TourCode = formatVal($("#txt_TourCodeLong"));
    //GJGD-1024 end

    if (objPolicy.RebateEx.ShareflightMade == "B") {
        objPolicy.RebateEx.ShareFlightReward = formatVal($("#txt_ShareFlightReward_B"));
    } else if (objPolicy.RebateEx.ShareflightMade == "D") {
        objPolicy.RebateEx.ShareFlightReward = formatVal($("#txt_ShareFlightReward_D"));
    } else {
        objPolicy.RebateEx.ShareFlightReward = 0;
    }

    //info
    //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
    //if (("1010,1001,0010").indexOf(objPolicy.Policy.ObTypeNum) > -1) {
    if ($('#td_ObTypeNum :radio:checked').data('Octr').T == '') {
        //edit by qiuzhicheng 2015.02.02 GJGD-707 end
        objPolicy.Info = null;
    } else {
        objPolicy.Info = {};
        objPolicy.Info.Findex = 2;
        //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
        //objPolicy.Info.DepCity = $("#dv_TransferCity").airPortSelect(null, "getSelectedAirPort");
        var airportTransfer = $("#dv_TransferCity").airPortSelect(null, "getAirPortSelectExcept");
        objPolicy.Info.DepCity = airportTransfer.select;
        //edit by qiuzhicheng 2015.02.02 GJGD-707 end
        if (objPolicy.Info.DepCity == '') {
            alert("请选择中转地！");//edit by qiuzhicheng 2015.02.02 GJGD-707
            return;
        }
            //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
            //else if (objPolicy.Policy.ArrCity.length > 8000) {        
            //alert("中转城市选择不要超过2000个，可以按洲际分开投放政策！");
        else if (!checkAirprtMaxLength(objPolicy.Info.DepCity, '中转', 'select')) {
            return;
        }
        //add by qiuzhicheng 2015.02.02 GJGD-707 begin
        objPolicy.Info.DepExcept = airportTransfer.except;
        if (!checkAirprtMaxLength(objPolicy.Info.DepExcept, '中转', 'except')) {
            return;
        }
        //add by qiuzhicheng 2015.02.02 GJGD-707 end
        objPolicy.Info.Cabin = $("#dv_TransferCity").airPortSelect(null, "getSelectedCabin");
        if (objPolicy.Info.Cabin == '') {
            alert("请选择中转舱位！");//edit by qiuzhicheng 2015.02.02 GJGD-707
            return;
        }
        //edit by qiuzhicheng 2015.02.02 GJGD-707 begin
        //objPolicy.Info.ArrCity = $("#dv_ArrCity").airPortSelect(null, "getSelectedAirPort");
        objPolicy.Info.ArrCity = airportArr.select;
        objPolicy.Info.ArrExcept = airportArr.except;
        //edit by qiuzhicheng 2015.02.02 GJGD-707 end
        objPolicy.Info.FlightType = objPolicy.Policy.FlightType;
        objPolicy.Info.Remark = objPolicy.Policy.Remark;
        objPolicy.Info.Agio = 0;
        objPolicy.Info.AddMoney = 0;
    }
    //前台缺口需审核默认不勾选
    objPolicy.Rebate.NotchProcessNeedReview = 0;
    if (objPolicy.Rebate.NotchProcess == '' || objPolicy.Rebate.NotchProcess == undefined) {
        alert("缺口程选项不能为空!");
        $("#rd_NotchProcess").find("input[type='radio']").first().focus2();
        return;
    }
    //if (objPolicy.Rebate.NotchProcess == 3 && objPolicy.Rebate.NotchProcessCity.trim() == '') {
    //    alert("请指定适用国家内缺口的国家");
    //    $("#txt_NotchProcessCity").focus2();
    //    return;
    //}
    if ((objPolicy.RebateEx.ShareflightMade == '' || objPolicy.RebateEx.ShareflightMade == undefined) && objPolicy.RebateEx.ShareFlightReward == 0) {
        alert("“共享航班”选项不能为空");
        return;
    }

    if (objPolicy.RebateEx.ShareFlightReward != 0) {
        if (objPolicy.RebateEx.ShareflightMade.indexOf('D') >= 0 && objPolicy.RebateEx.ShareFlightReward > 99.9) {

            $("#txt_ShareFlightReward_D").addClass("err").focus();
            alert("共享段指定奖励不能大于99.9%");
            return;
        }
        else if (objPolicy.RebateEx.ShareflightMade.indexOf('B') >= 0 && objPolicy.RebateEx.ShareFlightReward > 99.9) {

            $("#txt_ShareFlightReward_B").addClass("err").focus();
            alert("全程指定奖励不能大于99.9%");
            return;
        }
    }

    if (!$("#cb_AutoAgent").is(":checked")) {
        objPolicy.Rebate.AutoAgent = -1;
    }

    //供应上下班时间表
    fillTimeDataToJson();

    if ($("#cb_IsAuto").is(":checked") && $("#txt_LuggageAllowanceValue").val() == "") {
        objPolicy.Rebate.LuggageAllowanceValue = "-1";
    } else if (!$("#cb_IsAuto").is(":checked")) {
        objPolicy.Rebate.LuggageAllowanceValue = "-1";
    }

    //适用与不适用航班表
    objPolicy.ApplyFlightG = $.trim($("#txt_ApplyFlightG").val());
    objPolicy.ApplyFlightR = $.trim($("#txt_ApplyFlightR").val());
    objPolicy.UnApplyFlight = $.trim($("#txt_UnApplyFlight").val());

    //来回程不适用时间表
    objPolicy.UnApplyTimeS = '';
    objPolicy.UnApplyTimeE = '';
    var unTimeS = $("#td_UnApplyTimeS").dateRange(null, "getValue");
    var unTimeE = $("#td_UnApplyTimeE").dateRange(null, "getValue");
    $(unTimeS).each(function () {
        objPolicy.UnApplyTimeS += this.Start.pattern("yyyy-MM-dd") + "~" + this.End.pattern("yyyy-MM-dd") + ";";
    });
    $(unTimeE).each(function () {
        objPolicy.UnApplyTimeE += this.Start.pattern("yyyy-MM-dd") + "~" + this.End.pattern("yyyy-MM-dd") + ";";
    });

    //儿童享受直减  勾选 0（默认）   不勾选 1
    if ($("#cb_ChildrenReduction").is(":checked")) {
        objPolicy.RebateEx.ChildrenReduction = 0;
    } else {
        objPolicy.RebateEx.ChildrenReduction = 1;
    }


    if ($("#cb_IsAuto").is(":checked") && $("input:checkbox[name='cb_IsThreeAgreement']").is(":checked")) {
        objPolicy.Rebate.IsThreeAgreement = $("input:checkbox[name='cb_IsThreeAgreement']:checked").val();
        objPolicy.Rebate.AgentCode = $("#sl_AgentCode").val();
        var agentCodeText = objPolicy.Rebate.AgentCode;

        if (agentCodeText == '') {
            alert("提示：请填写自动出票大客户号");
            return;
        }
        alert("提示：自动出票将由大客户号【" + agentCodeText + "】开票！");
    } else {
        objPolicy.Rebate.IsThreeAgreement = 0;
        objPolicy.Rebate.AgentCode = "";
    }

    //GJGD-4252
    var isCategory = $("#td_IsCategory").find("input[type='checkbox']:checked").first().val();
    if (isCategory == "A" && !$("#cb_IsAuto").is(":checked")) {
        if (!$("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").is(":checked")) {
            //alert("提示：请选择无位时是否可做空编!");
            //$("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").first().addClass("err").focus();
            //return;
            objPolicy.Rebate.NoSetIsEmptyCodeTicket = 0;
        } else
            objPolicy.Rebate.NoSetIsEmptyCodeTicket = $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']:checked").val();
    } else {
        objPolicy.Rebate.NoSetIsEmptyCodeTicket = 0;
    }


    if ($("#txt_ShareFlightDiscount").val() == "") {
        objPolicy.RebateEx.ShareFlightDiscount = -1;
    }

    //检查是否是自动出票的政策，如果是给出提示。
    try {
        if (CheckIsAutoDrawTicket(objPolicy)) {
            alert("温馨提示：您的政策符合自动出票条件，建议勾选。");
        }
    }
    catch (e) {

    }
    if (objPolicy.Rebate.RefundGrade == 1) {
        objPolicy.Rebate.DrawerTicket = 0;
        objPolicy.Rebate.RescheduledGrade = 0;
    }

    $.ajax({
        type: "POST",
        url: ajaxUrl + '?method=SavePolicy',
        data: { Policy: window.JSON.stringify(objPolicy), oldPolicy: oldPolicy, Isguarantees: isguarantees, RefundAddMoney: refundAddMoney },
        success: function (result) {
            if (parseInt(result) > 0) {
                if (parent.AppMy != undefined) {
                    parent.AppMy.hide();
                }
                else {
                    window.history.go(-1);
                }
                //}           
            }
            else {
                alert("数据录入不完整，保存失败！");
            }
        }
    });

}
function CheckIsAutoDrawTicket(objP) {
    if (objP.Policy.State == undefined && autoState != "0" && autoState != "1"
  && autoState != "2") {
        return false;
    }
    if (objP.Policy.State != undefined && objP.Policy.State != "0" && objP.Policy.State != "1"
        && objP.Policy.State != "2") {

        return false;
    }
    var nowdate = new Date();
    var ticketE = new Date(objP.Policy.TicketE);
    var saleEDate = new Date(objP.Policy.SaleEDate);
    if (!compareDate(nowdate, ticketE) || !compareDate(nowdate, saleEDate)) {
        return false;
    }
    if (objP.Rebate.IsAuto || objP.Rebate.IsCategory != "A") {
        return false;
    }

    var ret = false;
    $.ajax({
        type: "POST",
        url: ajaxUrl + '?method=CheckAutoDrawTicket',
        async: false,
        data: { Provider: objP.Policy.Provider, TicketOffice: objP.Policy.TicketOffice },
        success: function (result) {
            if (result == "1") {

                ret = true;

            }
            else {
                ret = false;
            }
        }
    });

    return ret;

}
function compareDate(startDate, endDate) {
    var startdate = startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getDate();
    var date = new Date(startdate);
    var dateTime = date.getTime();
    if (dateTime <= endDate.getTime())
        return true;
    else
        return false;

}
//输入框填充到json
function simpleTextJsonFill(code, data) {
    $('[fm=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'id');
        data[key] = formatVal(n);
    });
}
//单选框填充到json
function simpleRadioJsonFill(code, data) {
    $('[rd=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'id');
        data[key] = formatVal($(":radio[checked='checked']", n));
    });
}
//复选框填充到json
function simpleCheckBoxJsonFill(code, data) {
    $('[cb=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'id');
        if (n.disabled != true && $(n).val() != '') {
            if (n.checked) {
                data[key] = formatVal(n);
            }
            else { data[key] = $(n).attr("class") != undefined && $(n).attr("class").indexOf("num") > -1 ? 0 : ''; }
        }
    });
}
function simpleCheckBoxJsonByNameFill(code, data) {
    $('[cbn=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'name');
        var name = 'cb_' + key;
        $(':checkbox[name=' + name + ']').each(function (i, n) {
            if ($(this).is(':checked')) {
                data[key] = $(this).val();
                //if (key == 'RefundGrade' && $(this).val() == 1) {
                //    data["RescheduledGrade"] = 0;
                //}
            }
        });
    });
}
//复杂复选框填充到json
function complexCheckBoxJsonFill(code, data, sign) {
    $('[cbx=' + code + ']').each(function (i, n) {
        var key = getKey(n, 'id');
        data[key] = '';
        $(':checkbox:not[value!=""]', n).each(function (j, m) {
            if ($(m).attr('cb') == undefined && m.disabled != true && m.checked) {
                data[key] += $(m).val() + sign;
            }
        });
        if (data[key] != '')
            data[key] = data[key].substr(0, data[key].length - 1);
    });
}
//时间数据填充到Json
function fillTimeDataToJson() {
    $(".selc>select").each(function (i, n) {
        var key = n.id.substr(4, n.id.length - 6);
        if (i % 4 == 0) {
            objPolicy[key] = '';
        }
        //objPolicy[key] = objPolicy[key] == undefined ? '' : objPolicy[key];
        if (n.disabled == false || n.disabled == undefined) {
            if ($(n).attr('dateType') == 'H') {
                objPolicy[key] += n.value + ":";
            }
            else if ($(n).attr('dateType') == 'M') {
                objPolicy[key] += n.value + "-";
            }
        }
    });
}
//格式化数据
function formatVal(obj) {
    if ($(obj).attr("class") != undefined) {
        if ($(obj).attr("class").indexOf("num") > -1) {
            if ($(obj).val() != '' && $(obj).attr('disabled') != 'disabled') {
                return parseInt($(obj).val());
            }
            else if ($(obj).attr("id") == 'txt_AutoAgent') { return -1; }
            else { return 0; }
        }
        else if ($(obj).attr("class").indexOf("float") > -1) {
            return $(obj).val() != '' ? parseFloat($(obj).val()) : 0;
        }
        else {
            if ($(obj).attr("class").indexOf("_date") > -1 && $(obj).val() == '')
                return null;
            return $(obj).val() != '' ? $(obj).val() : '';
        }
    }
    else {
        if ($(obj).attr("class") != undefined && $(obj).attr("class").indexOf("_date") > -1 && $(obj).val() == '')
            return null;
        return $(obj).val() != '' ? $(obj).val() : '';
    }

}
function CheckRetreatDiscountAndAgio() {
    var result = true;
    var discount = parseFloat($("#txt_Discount").val());
    var agio = parseFloat($("#txt_Agio").val());
    var retreatDisCount = $("#txt_RetreatTicketDiscount");
    var retreatAgio = $("#txt_RetreatTicketAgio");
    var retreatAgioF = parseFloat(retreatAgio.val());
    if (parseFloat(retreatDisCount.val()) < discount) {
        alert("退票政策代理费必须大于等于原代理费");
        retreatDisCount.focus();
        return false;
    }
    if (retreatAgioF < (agio + 0.2).toFixed(1) || retreatAgioF > (agio + 1).toFixed(1)) {
        alert("退票政策奖励必须大于等于原奖励+0.2且小于等于原奖励+1.0");
        retreatAgio.focus();
        return false;
    }
    return result;
}
function CheckRefundAddMoney() {
    var refundAddMoneytxt = $.trim($("#txt_RefundAddMoney").val());
    if (refundAddMoneytxt == '') {
        alert("退票服务费不能为空。");
        $("#txt_RefundAddMoney").focus();
        return false;
    }
    var ref = /^\d*$/;
    if (!ref.test(refundAddMoneytxt)) {
        alert("退票服务费必须是整数");
        $("#txt_RefundAddMoney").focus();
        return false;
    }
    var refundAddMoney = parseInt(refundAddMoneytxt);
    GetCurrency(false);
    var changePnr = $("#dv_IsChangePnr").find("input[type='radio']:checked").first().val();
    var isCategory = $("#td_IsCategory").find("input[type='checkbox']:checked").first().val();
    var refundAddRMB = refundAddMoney * currencyRate;
    var maxRMB = 80;
    if (changePnr == 'A' || changePnr == 'C' || changePnr == 'E') {
        var Sgds = $("#Sgds").val();
        if (Sgds != '0' && isCategory == 'C') {
            maxRMB = 80;
        }
    }
    else {
        if (isCategory == 'A' || isCategory == 'B') {
            maxRMB = 20;
        }
    }
    if (refundAddRMB > maxRMB || refundAddRMB < 1) {
        var currencyRateFixed = parseFloat(currencyRate).toFixed(4);
        alert("当前的汇率(" + currencyRateFixed + ")计算出的人民币金额为" + refundAddRMB + "(" + refundAddMoney + "*" + currencyRateFixed + "),退票服务费必须为1-" + maxRMB + "元");
        $("#txt_RefundAddMoney").focus();
        return false;
    }

    return true;
}
function ShowEle() {
    $('#sp_RetreatFee').show();
    if ($('#cb_Isguarantees').is(":checked")) {
        $('#RetreatTicket').show();
    }
    else {
        $('#RetreatTicket').hide();
    }
    document.getElementById("txt_RetreatTicketDiscount").disabled = false;
}

function Hidden() {
    $('#sp_RetreatFee').hide();
    $('#RetreatTicket').hide();
    $('#cb_Isguarantees').attr("checked", false);
    document.getElementById("txt_RetreatTicketDiscount").disabled = true;
}
//检查录入合法性
function CheckInput(obj) {

    var bl = true;
    if (obj == undefined) {
        if ($("#cb_Isguarantees").is(":checked")) {
            if ($.trim($("#txt_RetreatTicketAgio").val()) == '') {
                alert("退票奖励不能为空");
                return false;
            }
            if ($.trim($("#txt_RetreatTicketDiscount").val()) == '') {
                alert("退票代理费不能为空");
                return false;
            }
            if (!CheckRetreatDiscountAndAgio())
                return false;
            if (!CheckRefundAddMoney())
                return false;
        }
        if (!verify($("input[type='checkbox']", $("#td_FlightType"))[0]))
            return false;
        //add by qiuzhicheng 2015.04.13 GJGD-1262 begin
        if (!verify($("input[type='checkbox']", $("#td_IsCategory"))[0]))
            return false;
        if (!verify($("input[type='radio']", $("#div_ProtocolType"))[0]))
            return false;
        //add by qiuzhicheng 2015.04.13 GJGD-1262 end
        //GJGD-1596 20150613 ZH START
        //if ($("#cb_IsAuto").is(":checked")) {
        //    if (!verify($("input[type='radio']", $("#div_IsThreeAgreement"))[0]))
        //        return false;
        //}
        //GJGD-1596 20150613 ZH OVER
        isFocus = true;

        //GJJSZC-501 添加政策类型选择校验，航司校验
        if (!verify($("input[type='checkbox']", $("#td_FlightType"))[0]))
            return false;
        //if (!verify( $("#Itinerary")))
        //    return false;
        if (!verify($("#Sgds")))
            return false;
        //GJGD-1051 政策有效期修改校验 2015-3-9 add by lihui
        //$("#txt_SaleSDate,#txt_SaleEDate").blur();//del by qiuzhicheng 2015.04.24 转移至CheckDateRange
        //GJGD-1051 end 
        $("input[type='text']").each(function () {
            if (this.disabled != true && $(this).css("visibility") != 'hidden') {
                bl = verify(this);
                return bl;
            }
        });
        //add by qiuzhicheng 2015.04.24 begin
        if (!bl) {
            return false;
        }
        //add by qiuzhicheng 2015.04.24 end
        //add by qiuzhicheng 2015.04.16 GJGD-1288 begin
        if ($('#cb_IsReward').is(':checked') && $('#cb_RoundMustSpace').is(':checked')) {
            alert('“允许混舱1/2RT”和“往返必须包含舱位”不能同时使用');
            $('#cb_IsReward').focus();
            return false;
        }
        //add by qiuzhicheng 2015.04.16 GJGD-1288 end
        //add by qiuzhicheng 2015.04.24 begin
        if (!CheckDateRange()) {
            return false;
        }
        //add by qiuzhicheng 2015.04.24 end
        //add by qiuzhicheng 20150511 GJGD-1420 begin
        if (!checkAddMoneys()) {
            return false;
        }

        //add by qiuzhicheng 20150511 GJGD-1420 end
        //add by qiuzhicheng 20150507 begin   二字码
        //BSP 票本包括 BSP和B2B同时勾选的，这种政策保存时校验：是否勾选：“需供应商审核”，如果勾选，
        //那么给出提示：“BSP票本不需要供应商审核，请取消勾选”，且政策不能保存。只有取消勾选，才能保存
        //BSP票本的政策，如果后台勾选了："需供应商审核"后保存了政策 供应商再次修改政策时不用校验：BSP不能勾选需供应商审核 edit by qiuzhicheng 20150728 GJGD-1650
        //if ($($('#td_IsCategory').find('input:checkbox').get(0)).is(':checked') && $('#cb_MustProviderReview').is(':checked')) {

        if ($('#cb_MustProviderReview').is(':checked') && (objPolicy == undefined || objPolicy.Rebate.IsAdminMustProviderReview != 1)) {
            alert('政策不需要供应商审核，请取消勾选');
            $('#cb_MustProviderReview').focus();
            return false;
        }


        //add by qiuzhicheng 20150507 end
        //add by qiuzhicheng 20150515 GJGD-1353 begin
        if ($('#txt_AgioIncrement').val() != '' && (parseFloat($('#txt_Agio').val()) + parseFloat($('#txt_AgioIncrement').val()) > 100)) {
            alert('返点自增和奖励之和不能超过100，请重新设置');
            $('#txt_AgioIncrement').focus();
            return false;
        }

        if ($("#cb_ShareFlightOnlyApply").is(':checked')) {
            var re1 = /^([a-zA-Z0-9]{2}\/[a-zA-Z0-9]{2}\;)+$/;//多个航司对
            var re2 = /^(([a-zA-Z0-9]{2}\/[a-zA-Z0-9]{2}))$/;//单个航司对

            var val = $("#txt_ShareFlightOnlyApply").val();

            if (val == "") {
                $("#txt_ShareFlightOnlyApply").focus2();
                alert("勾选了'仅以下集团航司共享时给全部奖励',请填写对应的航司！");
                return false;
            }
            else if (!re1.test(val) && !re2.test(val) && val.toUpperCase() != "ALL") {
                $("#txt_ShareFlightOnlyApply").focus2();
                alert("请输入航司对，格式 MU/FM 或者 MU/FM;SQ/MI;");
                return false;
            }
        }

        //add by qiuzhicheng 20150515 GJGD-1353 end
        //add by qiuzhicheng 20150616 begin
        //if ($('#cb_IsReward').is(':checked') && ($('#hid_PolicyGroup').val() == '' || $('#hid_PolicyGroup').val() == '0')) {
        //    alert('如果勾选了允许混舱1/2RT，那么文件编号不能为空');
        //    $('#txt_PolicyGroup').focus();
        //    return false;
        //}
        //add by qiuzhicheng 20150616 end
    }
    else {
        isFocus = false;
        bl = verify(obj);
    }
    return bl;
}
//文本框失去焦点时校验录入合法性
function verify(obj) {
    var tit = "";
    if (obj.type == 'text' && $(obj).parent().css("visibility") != 'hidden' && obj.disabled != true) {
        if ($.trim(obj.value) == '' || $.trim(obj.value) == $(obj).attr("data-empty")) {
            if ($(obj).parent().prev().find(".bitian").length > 0) {
                tit = $.trim($(obj).parent().prev().html()).replace("*", "") + " 不能为空！";
                if (isFocus) {
                    $(obj).focus2();
                }
                $(obj).addClass("err");
                ShowErrorMsg(obj, tit);
                return false;
            }
            else if ($(obj).attr("class").indexOf("notnull") > -1 && !obj.disabled) {
                if (obj.id == "txt_RetrunAirport") {
                    tit = $.trim($(obj).prev().html()).substr($.trim($(obj).prev().html()).indexOf('>') + 1) + " 不能为空!";
                }
                else {
                    tit = $.trim($(obj).parent().prev().children().html()).substr($.trim($(obj).parent().prev().children().html()).indexOf('>') + 1) + " 不能为空!";
                }
                if (isFocus) {
                    $(obj).focus2();
                }
                $(obj).addClass("err");
                ShowErrorMsg(obj, tit);
                return false;
            }
        }
        else {
            return RegExpVerify(obj);
        }
    }
    else if (obj.type == 'checkbox') {
        if ($(obj).parent().parent().prev().find(".bitian").length > 0 && $(obj).parent().parent().find(":checkbox[checked='checked']").length == 0) {
            tit = "请选择 " + $.trim($(obj).parent().parent().prev().html()).replace("*", "").replace("：", "");
            $(obj).focus();
            ShowErrorMsg(obj, tit);
            return false;
        }
    }
        //add by qiuzhicheng 2015.04.13 GJGD-1262 begin
    else if (obj.type == 'radio') {
        if ($(obj).parent().parent().find('input[type=radio]:checked').length == 0) {
            tit = "请选择 " + $.trim($(obj).parent().parent().parent().prev().html()).replace("*", "").replace("：", "");
            $(obj).focus();
            ShowErrorMsg(obj, tit);
            return false;
        }
    }
    else if (obj.type == 'select-one' && $(obj).parent().css("visibility") != 'hidden' && $(obj).parent().disabled != true) {
        if ($.trim(obj.value) == '0') {
            if ($(obj).parent().prev().find(".bitian").length > 0) {
                tit = $.trim($(obj).parent().prev().html()).replace("*", "") + " 不能为空！";
                if (isFocus) {
                    $(obj).focus2();
                }
                $(obj).addClass("err");
                ShowErrorMsg(obj, tit);
                return false;
            }
        }
    }
    //add by qiuzhicheng 2015.04.13 GJGD-1262 end
    $(obj).removeClass("err");
    $("#errMsg").hide();
    return true;
}

//校验录入格式
function RegExpVerify(obj) {
    //add by qiuzhicheng 20150724 GJGD-1794 begin
    //票本是境外电子，那么供应商OFIICE号和开票OFFICE号只做长度限制，不做格式限制。长度限制在数据库表字段可存字符长度范围内即可
    if ($('#td_IsCategory input:checkbox[value="C"]').is(':checked') && ($(obj).attr('id') == 'txt_OrdinaryOffice' || $(obj).attr('id') == 'txt_TicketOffice')) {
        if ($(obj).val().length > 50) {
            if (isFocus) {
                $(obj).focus2();
            }
            $(obj).addClass("err");
            var tit = $.trim($(obj).parent().prev().html()).replace("<span class=\"bitian\">*</span>", "");
            ShowErrorMsg(obj, tit + "最大长度50");
            return false;
        } else {
            clearTimeout(_tmr);
            $(obj).removeClass("err");
            $("#errMsg").hide();
            return true;
        }
    }

    //Add 2015-9-9 GJGD-2044
    if ($('#td_IsCategory input:checkbox[value="C"]').is(':checked') && obj.id == "txt_TicketPlace") {
        if ($.trim($(obj).val()) == "") {
            //alert("开票地不能为空");
            $(obj).focus();
            return false;
        }
    }
    //End  GJGD-2044



    //add by qiuzhicheng 20150724 GJGD-1794 end
    if ($(obj).attr("regtxt") != undefined && $(obj).attr("regtxt") != '') {
        var reg = new RegExp($(obj).attr("regtxt"));
        if (!reg.test(obj.value)) {
            var tit = $.trim($(obj).parent().prev().html()).replace("<span class=\"bitian\">*</span>", "");
            if ($(obj).attr("tletype") == 'p') {
                tit = $.trim($(obj).prev().html()).substr($.trim($(obj).prev().html()).indexOf('>') + 1);
            }
            else if ($(obj).attr("tletype") == 'Pc') {
                tit = $.trim($(obj).parent().prev().children().html()).substr($.trim($(obj).parent().prev().children().html()).indexOf('>') + 1);
            }
            if (tit != "" && tit.toLowerCase().indexOf("<select") >= 0) {
                tit = tit.substr(tit.indexOf("selected>") + 9);
                if (tit.indexOf("<") > 0)
                    tit = tit.substr(0, tit.indexOf("<"));
            }
            if ($(obj).attr('id') == 'txt_IsShare') {
                tit += "  格式不正确！" + ($(obj).attr("data-empty") != undefined ? $(obj).attr("data-empty").replace('同一集团的航司,', '') : '');
            }
            else if ($(obj).attr('id') == 'txt_ShareFlightDiscount') {
                tit = "  格式不正确！" + ($(obj).attr("data-empty") != undefined ? $(obj).attr("data-empty") : '');
            }
            else {
                tit += "  格式不正确！" + ($(obj).attr("data-empty") != undefined ? $(obj).attr("data-empty") : '');
            }

            if (isFocus) {
                $(obj).focus2();
            }
            $(obj).addClass("err");
            ShowErrorMsg(obj, tit);
            return false;
        }
    }
    //add by qiuzhicheng 2015.03.27 begin
    if (obj.id == "txt_RetrunAirport") {
        var txt = $.trim($(obj).val()).toUpperCase();
        $(obj).val(txt);
        var oRetrunAirport = checkRetrunAirport(txt);
        if (oRetrunAirport.result === false) {
            if (isFocus) {
                $(obj).focus2();
            }
            $(obj).addClass("err");
            ShowErrorMsg(obj, oRetrunAirport.msg);
            return false;
        }
    }
    //add by qiuzhicheng 2015.03.27 end
    if (obj.id == 'txt_IsShare' && obj.value.toUpperCase().indexOf($("#hd_AirLine").val()) > -1) {
        if (isFocus) {
            $(obj).focus2();
        }
        $(obj).addClass("err");
        ShowErrorMsg(obj, "不允许填写【航空公司】中二字码");
        return false;
    }
    clearTimeout(_tmr);
    $(obj).removeClass("err");
    $("#errMsg").hide();
    return true;
}

//显示错误信息
var _tmr = null;
function ShowErrorMsg(obj, tit, plusPx) {
    clearTimeout(_tmr);
    if (plusPx == undefined)
        plusPx = 30;
    if (window.location.href.indexOf("?id") < 0 || window.location.href.indexOf("copyType") > -1)
        //edit by qiuzhicheng 2015.02.02 GJGD-707 begin 现在编辑政策时禁用父画面的滚动条，因此滚动自己就行
        //parent.document.body.scrollTop = $(obj).position().top - 5;
        document.body.scrollTop = $(obj).position().top - 5;
        //edit by qiuzhicheng 2015.02.02 GJGD-707 end
    else
        document.body.scrollTop = $(obj).position().top - 5;
    $("#errMsg").css({ top: $(obj).position().top + plusPx, left: $(obj).position().left });
    $("#errMsg").html(tit);
    if ($("#errMsg").css("display") != 'none')
        $("#errMsg").hide();
    $("#errMsg").slideToggle(500);
    _tmr = setTimeout(function () { $("#errMsg").slideToggle(500) }, 3000);
}

//复制政策
function CopyPolicyNew(pid) {
    if (confirm("保存成功！是否复制刚才保存的政策？")) {
        elB.confirm({
            tle: "复制政策",
            css: "padding: 0 0",
            msg: "<div id=\"div_ObTypeNum\" style=\"padding:10px 0 10px 15px;\">" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"1010\" checked=\"checked\" />复制添加国内始发</label><br/>" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"0110\" />复制添加国内始发Add-On</label><br/>" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"0111\" />复制添加国内始发中转</label><br/>" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"1001\" />复制添加直飞SOTO</label><br/>" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"0101\" />复制添加国外始发Add-On</label><br/>" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"0113\" />复制添加国外始发中转</label><br/>" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"0010\" />复制添加境外电子票</label><br/>" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"0112\" />复制添加境外中转电子票</label><br/>" +
                "<label><input type=\"radio\" name=\"typenum\" value=\"0114\" />复制添加境外境内境外</label>" +
                "</div>"
                ,
            back: false,
            width: 330,
            isClose: true,
            buttonList: [{
                id: "", text: "确定复制", bak: function () {
                    window.location.href = "/Provider/NewPolicy/Policy/PolicyPersistence.aspx?id=" + pid + "&copyType=" + $("#div_ObTypeNum input:radio[checked='checked']").val() + "&tab=false";

                }
            },
            {
                id: "", text: "取消", bak: function () {
                    //window.parent.document.getElementById('btn_Search').click();
                    parent.AppMy.hide();
                }
            }]
        });
    }
    else {
        //window.parent.document.getElementById('btn_Search').click()
        parent.AppMy.hide();
    }
}

function getDataName(datas, key) {
    var name = '';
    for (var i = 0; i < datas.length; i++) {
        if (datas[i].Key == key) {
            name = datas[i].Name;
            break;
        }
    }
    return name;
}

function NoSetIsEmptyCodeTicketIsShow() {
    //GJGD-4587 注销取消勾选“自动出票”时显示“无位是否接受做空编”
    //var iscategory = $("#td_IsCategory").find("input[type='checkbox']:checked").first().val();
    //var isAuto = $("#cb_IsAuto").is(":checked") ? true : false;
    //if (iscategory == 'A' && !isAuto) {
    //    $("#td_NoSetIsEmptyCodeTicket").show();
    //} else {
    //    $("#td_NoSetIsEmptyCodeTicket").hide();
    //    $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
    //}
    //GJGD-4587 注销取消勾选“自动出票”时显示“无位是否接受做空编”
}


//add qiuzhicheng 2015.03.27 begin
function checkRetrunAirport(txt) {
    var countryArray = new Array();
    var airportArray = new Array();
    var oRet = { 'result': false, 'msg': '' };
    var arr = txt.split('/');

    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == '') {
            continue;
        }
        if (arr[i].length == 2) {
            if (!/^([A-Z]{2})+$/.test(arr[i])) {
                oRet.msg = '请输入正确的国家二字码';
                return oRet;
            } else {
                countryArray.push(arr[i]);
            }
        } else if (arr[i].length == 3) {
            if (!/^([A-Z]{3})+$/.test(arr[i])) {
                oRet.msg = '请输入正确的机场三字码';
                return oRet;
            } else {
                airportArray.push(arr[i]);
            }
        } else {
            oRet.msg = '请输入正确的国家二字码或机场三字码';
            return oRet;
        }
    }
    if (oGlobalData) {
        //检测是否有不存在的CODE
        if (oGlobalData.country) {
            for (var i = 0; i < countryArray.length; i++) {
                var code = countryArray[i];
                if (!oGlobalData.country[code]) {
                    oRet.msg = '国家二字码' + code + '不存在!';
                    return oRet;
                }
            }
        }
        if (oGlobalData.airport) {
            for (var i = 0; i < airportArray.length; i++) {
                var code = airportArray[i];
                if (!oGlobalData.airport[code]) {
                    oRet.msg = '机场三字码' + code + '不存在!';
                    return oRet;
                }
            }
        }
    }
    oRet.result = true;
    return oRet;
}
function changeCopySelect(oldType, select, except) {
    return select;
}
function changeCopyExcept(oldType, select, except) {
    return except;
}
//add qiuzhicheng 2015.03.27 end
//add by qiuzhicheng 2015.04.16 GJGD-1288 begin
function checkAirprtMaxLength(value, typeName, selectexcept) {
    var maxLength = 8000;
    var warningLength = 400;
    if (value.length > maxLength) {
        alert('您选择的方式不支持，请重新选择。');
        return false;
    } else if (value.length > warningLength) {
        var msg = '您' + (selectexcept == 'select' ? '选择' : '排除') + '的' + typeName + '机场或者国家较多，不利于维护。\n';
        msg += '您可以直接勾选相应的【中国境内】、【境外】、【全球】、【国家】，再排除部分不适用的【机场】、【国家】来选择。\n';

        //msg += '点击【确定】继续提交，点击【取消】重新选择。';
        //return confirm(msg);

        msg += '请重新选择。';//不再温馨了
        alert(msg);
        return false;
    } else {
        return true;
    }
}
//add by qiuzhicheng 2015.04.16 GJGD-1288 end
//add by qiuzhicheng 2015.04.20 GJGD-1293 begin

function setNoOutTicketOffice() {

    if ($('#cb_NoOutTicketOffice').is(':checked')) {
        $('#sp_NoOutTicketOfficeInfo').find('input').removeAttr('disabled', 'disabled');
        if (!($('#NoOpenTicket').is(':checked'))) {
            $('#NoOpenTicket').attr('disabled', 'disabled');

        }
        else {
            $('#NoOpenTicket').removeAttr('disabled', 'disabled');
        }

    } else {
        $('#sp_NoOutTicketOfficeInfo').find('input').attr('disabled', 'disabled');
        $('#txt_NoOutTicketOffice').val('').emptyValue();
    }

}
function setNoOutTicketOfficeClick() {
    if (!isLoaded)
        return;

    if ($('#cb_NoOutTicketOffice').is(':checked')) {
        $('#sp_NoOutTicketOfficeInfo').find('input').removeAttr('disabled', 'disabled');
        if (allNoOpenTicketProiders.toLowerCase().indexOf(curUser.toLowerCase()) == -1) {
            $('#NoOpenTicket').attr('disabled', 'disabled');
            $('#ChangeCodeTicket').attr('checked', 'checked');

        }

    } else {
        $('#sp_NoOutTicketOfficeInfo').find('input').attr('disabled', 'disabled');
        $('#txt_NoOutTicketOffice').val('').emptyValue();
    }
}
//add by qiuzhicheng 2015.04.20 GJGD-1293 end
//add by qiuzhicheng 2015.04.24 begin 检查日期范围
function CheckDateRange() {
    var sdate = new Date($("#txt_SaleSDate").val().replace(/-/g, '/'));
    var edate = new Date($("#txt_SaleEDate").val().replace(/-/g, '/'));
    //GJGD-1051 2015-3-9 add by lihui
    if (sdate > edate) {
        alert("去程有效期结束日期不能早于开始日期，请重新选择去程有效期结束日期！");
        $("#txt_SaleEDate").focus();
        return false;
    }
    //开票有效期
    var sTicket = new Date($('#txt_TicketS').val().replace(/-/g, "/"));
    var eTicket = new Date($('#txt_TicketE').val().replace(/-/g, "/"));
    if (sTicket > edate) {
        alert("开票有效期开始日期超出范围，必须在去程有效期内");
        $("#txt_TicketS").focus();
        return false;
    }
    if (eTicket > edate) {
        alert("开票有效期结束日期超出范围，必须在去程有效期内");
        $("#txt_TicketE").focus();
        return false;
    }
    if (eTicket < sTicket) {
        alert("开票有效期结束日期不能早于开始日期，请重新选择开票有效期结束日期！");
        $("#txt_TicketE").focus();
        return false;
    }
    //回程有效期
    var eReturn;
    if ($("#txt_EReturnTrip").val() != "") {
        eReturn = new Date($("#txt_EReturnTrip").val().replace(/-/g, '/'));
        if (eReturn < edate) {
            alert("回程有效期延用日期不能早于去程有效期结束日期");
            $("#txt_EReturnTrip").focus();
            return false;
        }
    }
    //GJGD-1051 end
    //不适用
    var bln = true;
    $("#td_UnApplyTimeS .dateRange a").each(function () {
        var arr = $(this).html().split('—');
        if (new Date(arr[0].replace(/-/g, '/')) < sdate || new Date(arr[1].replace(/-/g, '/')) > edate) {
            $(this).click();
            alert("部分去程不适用日期超出去程有效期范围，如需要请重新添加");
            bln = false;
            return false;
        }
    });
    if (!bln) {
        return false;
    }
    $("#td_UnApplyTimeE .dateRange a").each(function () {
        var arr = $(this).html().split('—');
        if (eReturn) {
            if (new Date(arr[0].replace(/-/g, '/')) < sdate || new Date(arr[1].replace(/-/g, '/')) > eReturn) {
                $(this).click();
                alert("部分回程不适用日期超出回程有效期范围，如需要请重新添加");
                bln = false;
                return false;
            }
        }
    });
    if (!bln) {
        return false;
    }
    return true;
}
//add by qiuzhicheng 2015.04.24 end
//add by qiuzhicheng 20150511 GJGD-1420 begin
//新增或修改政策时：票本勾选BSP票本或BSP和B2B同时勾选，或者单独勾选B2B的，且奖励值为0，且单程/往返直减项 <= 2 。
//满足以上条件的新增政策，儿童票："不可开"静灰 不可勾选
var CHILDREN_STAT = '';
function setIsChildren() {
    if (($('#td_IsCategory input:checkbox[value="A"]').is(':checked') || $('#td_IsCategory input:checkbox[value="B"]').is(':checked'))
            && $('#txt_Agio').val() == '0'
            && (($('#txt_OneSubtracting').is(':enabled')
                    && ($('#txt_OneSubtracting').val() == '' || (!isNaN($('#txt_OneSubtracting').val()) && parseInt($('#txt_OneSubtracting').val()) <= 2)))
                || ($('#txt_RoundSubtracting').is(':enabled')
                    && ($('#txt_RoundSubtracting').val() == '' || (!isNaN($('#txt_RoundSubtracting').val()) && parseInt($('#txt_RoundSubtracting').val()) <= 2))))) {
        if (CHILDREN_STAT != 'DISABLED') {
            if ($('#sp_IsChildren input:radio[value="C"]').is(':checked')) {
                $('#sp_IsChildren input:radio[value="C"]').removeAttr('checked');
            }
            $('#sp_IsChildren input:radio[value="C"]').attr('disabled', 'disabled');
            CHILDREN_STAT = 'DISABLED';
        }
    } else {
        if (CHILDREN_STAT == 'DISABLED') {
            $('#sp_IsChildren input:radio[value="C"]').removeAttr('disabled');
            CHILDREN_STAT = '';
        }
    }
}

/*
 * 共享航班 设置空间之间的关联状态
 */
function setShareFlight() {

    if ($("#td_ShareflightMade input:radio[value='B']").is(":checked")) {
        //前台禁止选择该项(GJGD-4584 前台公布运价与私有政策可用)
        $("#txt_ShareFlightReward_B").removeAttr('disabled');
    } else {
        //$("#txt_ShareFlightReward_B").attr('disabled', 'disabled').val(0);
        $("#txt_ShareFlightReward_B").attr('disabled', 'disabled');
    }

    if ($("#td_ShareflightMade input:radio[value='D']").is(":checked")) {
        $("#txt_ShareFlightReward_D").removeAttr('disabled');
    } else {
        $("#txt_ShareFlightReward_D").attr('disabled', 'disabled');
    }

    var shareflightMadeVal = $("#td_ShareflightMade input:radio[name='rd_ShareflightMade']:checked").val();
    if (shareflightMadeVal != "B") {
        //$("#txt_ShareFlightReward_B").val(0);
    } else if (shareflightMadeVal != "D") {
        //$("#txt_ShareFlightReward_D").val(0);
    }
    if ($("#td_ShareflightMade input:checkbox[value='F']").is(":checked")) {
        $("#txt_ShareFlightOnlyApply").removeAttr('disabled');
    } else {
        $("#txt_ShareFlightOnlyApply").attr('disabled', 'disabled').val('');
    }
}

//凡是BSP票本或BSP和B2B同时勾选，或者单独勾选B2B的，开票费、儿童票的"加收手续费"、婴儿票的"加收手续费"字段 只允许输入：0-30 含0和30的整数
//edit by qiuzhicheng 20150724 GJGD-1794
function checkAddMoneys() {
    function checkAddMoney(obj, max) {
        if (obj.val() == '') {
            return true;
        }
        if (!new RegExp("^\\d*$").test(obj.val())) {
            return false;
        }
        if (parseInt(obj.val()) >= 0 && parseInt(obj.val()) <= max) {
            return true;
        } else {
            return false;
        }
    }
    function changeMoneyType(money) {//计算汇率金额取整
        return parseInt(money / currencyRate + '');
    }
    if ($('#td_IsCategory input:checkbox[value="A"]').is(':checked') || $('#td_IsCategory input:checkbox[value="B"]').is(':checked')) {
        if (!checkAddMoney($('#txt_AddMoney'), changeMoneyType(30))) {
            alert('票本类型选择了BSP或者B2B，开票费只能输入0到' + changeMoneyType(30) + '的整数');
            $('#txt_AddMoney').focus();
            return false;
        }
        if (!checkAddMoney($('#txt_ChildrenFee'), 30)) {
            alert('票本类型选择了BSP或者B2B，儿童票的"加收手续费"只能输入0到' + 30 + '的整数');
            $('#txt_ChildrenFee').focus();
            return false;
        }
        if (!checkAddMoney($('#txt_BabyFee'), 30)) {
            alert('票本类型选择了BSP或者B2B，婴儿票的"加收手续费"只能输入0到' + 30 + '的整数');
            $('#txt_BabyFee').focus();
            return false;
        }
    }
    //境外电子
    if ($('#td_IsCategory input:checkbox[value="C"]').is(':checked')) {
        //代理费和奖励都是0时，开票费限制在100以内（<=100）
        if ($('#txt_Discount').val() == '0' && $('#txt_Agio').val() == '0') {
            if (!checkAddMoney($('#txt_AddMoney'), changeMoneyType(100))) {
                alert('票本类型选择了境外电子，开票费只能输入0到' + changeMoneyType(100) + '的整数');
                $('#txt_AddMoney').focus();
                return false;
            }
        } else {
            //代理费和奖励任意一个不为零，开票费 限制在30以内（<=30）
            if (!checkAddMoney($('#txt_AddMoney'), changeMoneyType(30))) {
                alert('票本类型选择了境外电子，开票费只能输入0到' + changeMoneyType(30) + '的整数');
                $('#txt_AddMoney').focus();
                return false;
            }
        }
    }
    return true;
}
function PolicyGroupCode() {
    FreeInputJElass({
        input: 'txt_PolicyGroup',
        hidden: 'hid_PolicyGroup',
        url: ajaxUrl + '?method=GetProviderPolicyGroup',
        hintMsg: '请输入英文字母或者数字，最大长度50',
        regTxt: "^[a-zA-Z0-9]*$",
        defaultValue: '0'
    });
}
//add by qiuzhicheng 20150511 GJGD-1420 end
//新增政策时，勾选BSP，则不允许勾选“需供应商审核”
function setMustProviderReviewDisabled() {
    if (policyID == '') {
        if ($('#td_IsCategory input:checkbox[value="A"]').is(':checked')) {
            $('#cb_MustProviderReview').removeAttr('checked').attr('disabled', 'disabled');
        } else {
            $('#cb_MustProviderReview').removeAttr('disabled');
        }
    }
}
//只有政策勾选了往返，才可以勾选往返必须包含舱位 GJGD-1830
function setRoundMustSpaceDisabled() {
    if ($('#td_FlightType :checkbox[value="1"]').is(':checked')) {
        $('#cb_RoundMustSpace').removeAttr('disabled');
    } else {
        $('#cb_RoundMustSpace').removeAttr('checked').attr('disabled', 'disabled');
        $('#txt_RoundMustSpace').val('').attr('disabled', 'disabled').emptyValue();
    }
}
function setTicketPlaceRateHint() {
    if ($('#txt_TicketPlace').val() == '') {
        $('#spn_TicketPlaceRate').html() == '未设置';
    } else {
        $.ajax({
            url: ajaxUrl + '?method=GetCurrtypeAndRate&TicketPlace=' + $('#txt_TicketPlace').val(),
            type: 'post',
            success: function (result) {
                if (result != 'false') {
                    var array = result.split(',');
                    $('#spn_TicketPlaceRate').html(array[1]);
                }
            }
        });
    }
}
function TicketPlaceIsShow() {
    if ((!isExtProvider && !IsAddEtermConfigSupply) || ($('#Sgds').val() == "0") || ($('#Sgds').val() == "5")) {
        $("#td_TicketPlace").hide();
        $("#txt_TicketPlace").val("").hide();

        $("span[name='currtype']").each(function (i, n) {
            $(n).html(currTypeTemp);
        });
        currType = currTypeTemp;
        currencyRate = currencyRateDefaultRate;
    } else {
        $("#td_TicketPlace").show();
        $("#txt_TicketPlace").show();
    }
}
var LastShowAutoChangePnrInfo = "";
function AutoChangePnrSet() {
    var InputAirLines = $("#hd_AirLine").val() + "/" + $("#txt_IsShare").val();
    var IsShowAutoChangePnr = false;
    var IsCategory = $("#td_IsCategory").find("input[type='checkbox']:checked").first().val();
    var Sgds = $("#Sgds").val();
    var rd_ChangePnr = $("input[name='rd_ChangePnr']:checked").first().val();
    var _LastShowAutoChangePnrInfo = InputAirLines + IsCategory + Sgds + rd_ChangePnr;
    $(InputAirLines.split('/')).each(function (i, v) {
        if (v != "" && CanAutoChangePnrAirLines.indexOf(v.toUpperCase()) > -1) {
            //if (IsCategory != "C" || Sgds == "0")
            //IsShowAutoChangePnr = true;
        }
    });
    LastShowAutoChangePnrInfo = _LastShowAutoChangePnrInfo;
    return IsShowAutoChangePnr;
}

function BspAutoTicketIsChecked(isCategory, office, autoIsChecked) {
    if (isCategory == 'A' && office != '') {
        if (!$('#cb_IsAuto').is(':checked')) {
            setCheckBoxClick('#cb_IsAuto', true);
        }
        $(".tip_IsAuto").show();

        if (office != undefined && office != '') {
            $.ajax({
                url: ajaxUrl + "?method=CheckBspAuto",
                type: 'POST',
                data: { Office: office },
                success: function (data) {
                    if (data == "True") {
                        $(".tip_IsAuto2").hide();
                    } else {
                        //$(".tip_IsAuto2").show();

                        //GJGD-4559 非独立系统再显示
                        if ($('#table_ShowPlatform').css('display') == 'none') {
                            $(".tip_IsAuto2").show();
                        }
                        else {
                            $(".tip_IsAuto2").hide();
                        }
                        //GJGD-4559 非独立系统再显示
                    }
                }
            })
        }
    } else {
        if (!autoIsChecked) {
            setCheckBoxClick('#cb_IsAuto', false);
            C.Dom.setDisplay($('#tr_AutoSet,#tr_AutoSetTwo,#tr_LuggageAllowanceValue'), false);
        }
        $(".tip_IsAuto").hide();
        $(".tip_IsAuto2").hide();
    }
}

//GJGD-4587 政策前台判断自动换编与无编是否接受空编显示与否
$(function () {
    $('input:radio[name="rd_ChangePnr"]').click(function () {
        var rad = $('input:radio[name="rd_ChangePnr"]:checked').val();
        var bsp = $('#td_IsCategory input[type="checkbox"]:checked').val();
        if (bsp != null && bsp != 'A') {
            $('#IsAutoChangePnrLable').hide();
            $('#td_NoSetIsEmptyCodeTicket').hide();
            $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
            $("#IsAutoChangePnr").removeAttr('checked');
        }
        else {
            if (rad != null && (rad == 'A' || rad == 'C' || rad == 'E')) {
                $('#IsAutoChangePnrLable').show();
                $('#td_NoSetIsEmptyCodeTicket').show();
            }
            else {
                $('#IsAutoChangePnrLable').hide();
                $('#td_NoSetIsEmptyCodeTicket').hide();
                $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
                $("#IsAutoChangePnr").removeAttr('checked');
            }
        }
    });

    $('#td_IsCategory input[type="checkbox"]').click(function () {
        var bsp = $('#td_IsCategory input[type="checkbox"]:checked').val();
        if (bsp != null && bsp != 'A') {
            $('#IsAutoChangePnrLable').hide();
            $('#td_NoSetIsEmptyCodeTicket').hide();
            $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
            $("#IsAutoChangePnr").removeAttr('checked');
        }
        else {
            var rad = $('input:radio[name="rd_ChangePnr"]:checked').val();
            if (rad != null && (rad == 'A' || rad == 'C' || rad == 'E')) {
                $('#IsAutoChangePnrLable').show();
                $('#td_NoSetIsEmptyCodeTicket').show();
            }
            else {
                $('#IsAutoChangePnrLable').hide();
                $('#td_NoSetIsEmptyCodeTicket').hide();
                $("input:checkbox[name='cb_NoSetIsEmptyCodeTicket']").removeAttr('checked');
                $("#IsAutoChangePnr").removeAttr('checked');
            }
        }

    });
});
